package com.incar.chuxing.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.certification.CertifyCardActivity;
import com.incar.chuxing.activity.certification.CertifyDrivelicenseActivity;
import com.incar.chuxing.activity.driving.DrivingActivity;
import com.incar.chuxing.activity.personal.ContactServiceActivity;
import com.incar.chuxing.activity.personal.DebugModeActivity;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.activity.personal.TravelRecordActivity;
import com.incar.chuxing.adapter.CarsPagerAdapter;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.ParseApiStore;
import com.incar.chuxing.api.RxApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.GetAppConfig;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.baiduMap.LocationFilter;
import com.incar.chuxing.baiduMap.MapStatusUtils;
import com.incar.chuxing.baiduMap.MarkerOverlay.MarkerOverlay;
import com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils;
import com.incar.chuxing.baiduMap.RoutePlan;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.base.Resource;
import com.incar.chuxing.bean.AvatarEvent;
import com.incar.chuxing.bean.CancelOrder;
import com.incar.chuxing.bean.CarInfoBean;
import com.incar.chuxing.bean.CarListBean.AttachmentBean.ContentBean;
import com.incar.chuxing.bean.CheckCarOrderBean;
import com.incar.chuxing.bean.CheckPeccancyBean;
import com.incar.chuxing.bean.CheckUserAccountBean;
import com.incar.chuxing.bean.CityBoundBean;
import com.incar.chuxing.bean.CityDetailBean;
import com.incar.chuxing.bean.CommonResultBean;
import com.incar.chuxing.bean.ConfigEvent;
import com.incar.chuxing.bean.CountDownCloseEvent;
import com.incar.chuxing.bean.CountDownEvent;
import com.incar.chuxing.bean.CouponCountDownBean;
import com.incar.chuxing.bean.CurrentFeeBean;
import com.incar.chuxing.bean.DayRentPriceBean;
import com.incar.chuxing.bean.DrawerEvent;
import com.incar.chuxing.bean.ExistingTravel;
import com.incar.chuxing.bean.GetFirstCarEvent;
import com.incar.chuxing.bean.GetUnFinishedEvent;
import com.incar.chuxing.bean.GoldCarOneBean;
import com.incar.chuxing.bean.H5CancelOrderEvent;
import com.incar.chuxing.bean.InitBean;
import com.incar.chuxing.bean.OnLocationDoneEvent;
import com.incar.chuxing.bean.OnSplashFadeEvent;
import com.incar.chuxing.bean.OperateBean;
import com.incar.chuxing.bean.PecancyRedDotBean;
import com.incar.chuxing.bean.PlaceOrderBean;
import com.incar.chuxing.bean.PopPostBean;
import com.incar.chuxing.bean.PostNewBean;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.bean.RentDurationBean;
import com.incar.chuxing.bean.ResultBean;
import com.incar.chuxing.bean.ReturnCarCommentBean;
import com.incar.chuxing.bean.ReturnOilBean;
import com.incar.chuxing.bean.SendTelBean;
import com.incar.chuxing.bean.TabChangeEvent;
import com.incar.chuxing.bean.TravelDetailBean;
import com.incar.chuxing.bean.UnFinishedOrderBean;
import com.incar.chuxing.bean.WalletRedDotBean;
import com.incar.chuxing.bean.ZhiMaShouQuanBean;
import com.incar.chuxing.order.OnCheckOrderStatusListener;
import com.incar.chuxing.repository.OrderRepository;
import com.incar.chuxing.utils.AntiShake;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.DensityUtils;
import com.incar.chuxing.utils.DialogQueue;
import com.incar.chuxing.utils.Dialogs.CarCurrentParkFeeDialog;
import com.incar.chuxing.utils.Dialogs.ConfirmAbatementDialog;
import com.incar.chuxing.utils.Dialogs.ConfirmDayRentDialog;
import com.incar.chuxing.utils.Dialogs.DialogOneButton;
import com.incar.chuxing.utils.Dialogs.DialogTwoButton;
import com.incar.chuxing.utils.Dialogs.NeedRechargeDialog;
import com.incar.chuxing.utils.Dialogs.PostDialog;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.NetUtils;
import com.incar.chuxing.utils.RxBus;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.StateType;
import com.incar.chuxing.utils.SystemToastUtils;
import com.incar.chuxing.utils.ThreadPool;
import com.incar.chuxing.utils.TimeUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.ble.BluetoothHelper;
import com.incar.chuxing.utils.policecertify.APIService;
import com.incar.chuxing.utils.policecertify.Config;
import com.incar.chuxing.utils.policecertify.FaceException;
import com.incar.chuxing.utils.policecertify.PoliceAccessToken;
import com.incar.chuxing.utils.policecertify.PoliceOnResultListener;
import com.incar.chuxing.utils.wangyiqiyu.ConsultService;
import com.incar.chuxing.widget.CountDownIndicate;
import com.incar.chuxing.widget.CouponCountDown;
import com.incar.chuxing.widget.LoopViewPager;
import com.incar.chuxing.widget.MyRelativeLayout;
import com.incar.chuxing.widget.TabSwitchView;
import com.qiyukf.unicorn.api.Unicorn;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengCallback;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function3;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.wefor.circularanim.CircularAnim;

import static android.util.TypedValue.COMPLEX_UNIT_DIP;
import static com.baidu.location.BDLocation.TypeNetWorkLocation;
import static com.baidu.location.BDLocation.TypeOffLineLocation;
import static com.baidu.location.BDLocation.TypeServerError;
import static com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils.LOAD_ERROR;
import static com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils.LOAD_LOGOUT;
import static com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils.LOAD_SUCCESS;
import static com.incar.chuxing.utils.StateType.State.DEFAULT;
import static com.incar.chuxing.utils.StateType.State.PAGER_NEAR;
import static com.incar.chuxing.utils.StateType.State.PAGER_ONE_AND_NEAR;


public class MainActivity extends BaseActivity implements SensorEventListener {
    @BindView(R.id.main_title_tv_gx)
    TextView mainTitleTvGx;
    @BindView(R.id.main_title_tv_sx)
    TextView mainTitleTvSx;
    @BindView(R.id.main_title_tv_tan)
    TextView mainTitleTvTan;
    @BindView(R.id.layout_send_tv_service)
    TextView layoutSendTvService;
    @BindView(R.id.layout_tv_scan_license)
    TextView layoutTvScanLicense;
    private Context mContext = this;
    @BindView(R.id.imageView)
    GifImageView gifImageView;
    @BindView(R.id.splash)
    RelativeLayout splash;
    @BindView(R.id.rl_park_fee)
    RelativeLayout rlParkFee;

    private DrawerLayout drawer;
    public static TabSwitchView tabSwitchView;
    public static CouponCountDown couponCountdown;
    private TextView tx_reserve_order_timer, tx_place_order_plate, txInsure, findCarFee, useCar, centerUsername, long_click_tip, find_car_brandModel, find_car_qipao, find_car_current;
    private ImageView iv_order_car, imageViewLocate, imageViewCenter, imageView_main_card, imageView_card;
    private ImageView imageViewHead;
    private ImageButton find_car_find, find_car_open;
    private CheckBox abatementCheckBox;
    private RelativeLayout layout_car_pager, find_car_begin;
    private LinearLayout layout_find_car, contact_deliver;
    private BaiduMap mBaiduMap;
    private MapView mapView;
    private LocationClient mLocClient;
    private static final int PERMISSION_REQUEST_CODE = 1;
    private SensorManager mSensorManager;
    private MyLocationData locData;
    private float mCurrentAccuracy;
    private Double lastX = 0.0;
    private OverlayUtils overlayUtils;
    private MapStatusUtils mapStatusUtils;
    public LatLng curPosition;
    private LatLng foundCarPosition;
    private CarsPagerAdapter carsPagerAdapter;
    private LoopViewPager vpCar;
    private boolean isAnimatorShow = false;
    private boolean isFirstLocation = true;
    private boolean isLoadingDone = false;
    private String isInsuranceCheck;
    private CountDownTimer timer;//寻车倒计时
    private CountDownIndicate countDownIndicate;
    public boolean isExecuteOnResumeCheckOrder = true;//走了onNewIntent，onResume就不执行检查订单
    private boolean firstCalculateDistance = false;

    private ImageView iv_wallet_reddot, iv_weizhang_reddot;
    private DialogTwoButton unFinishTravelDialog;
    DialogQueue dialogQueue;

    @Override
    public void initCustomMapView() {
        //new MapStatusUtils().setMapCustomFile(this, "custom_config.json");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        dialogQueue = DialogQueue.getInstance();
        EventBus.getDefault().register(this);//注册EventBus
        initAccessToken();//获取Ocr的Token
        initPoliceAccessToken();//获取公安验证token;
        PushAgent.getInstance(this).enable(new IUmengCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
    }

    @Override
    public void initView() {
        splash.setVisibility(View.VISIBLE);
        gifImageView.setImageResource(R.drawable.logo_animation);
        unFinishTravelDialog = new DialogTwoButton(MainActivity.this);
        initMap();
        getPermissions();
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) == null) {//未登录
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        } else {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }

        long_click_tip = (TextView) findViewById(R.id.long_click_tip);
        imageViewLocate = (ImageView) findViewById(R.id.imageView_locate);
        imageViewCenter = (ImageView) findViewById(R.id.imageView_center);
        iv_wallet_reddot = (ImageView) findViewById(R.id.iv_wallet_reddot);
        iv_weizhang_reddot = (ImageView) findViewById(R.id.iv_weizhang_reddot);
        imageViewHead = (ImageView) findViewById(R.id.info_image_head);
        contact_deliver = findViewById(R.id.contact_deliver);
        imageView_main_card = findViewById(R.id.imageView_main_card);
        imageView_card = findViewById(R.id.imageView_card);
        if (BuildConfig.DEBUG) {//显示debug模式入口
            findViewById(R.id.debug_entry).setVisibility(View.VISIBLE);
        }

        centerUsername = (TextView) findViewById(R.id.center_username);
        useCar = (TextView) findViewById(R.id.use_car);
        findCarFee = (TextView) findViewById(R.id.find_car_fee_tip);
        initCarPagerLayout();
        initFindCarLayout();
        //监听drawer
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                centerUsername.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_NICK));
                if (!"0".equals(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE))) {
                    ImageLoader.getInstance().displayCricleImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE), imageViewHead);
                    MyApplication.getInstance().options.uiCustomization.rightAvatar = MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE);
                } else {
                    ImageLoader.getInstance().displayCricleImage(getApplicationContext(), R.drawable.icon_head, imageViewHead);
                    MyApplication.getInstance().options.uiCustomization.rightAvatar = "android.resource://" + mContext.getPackageName() + "/" + R.drawable.icon_head;
                }
                if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.PARK_FEE_ENTRY, 1) == 0) {
                    rlParkFee.setVisibility(View.GONE);
                } else {
                    rlParkFee.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        SPUtils.getInstance(mContext).putIntValue(SPKey.IS_CITY_OPEN, 0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRedDotBean(PecancyRedDotBean RedDotBean) {
        imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center));
        iv_weizhang_reddot.setVisibility(View.INVISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWalletRedDotBean(WalletRedDotBean RedDotBean) {
        imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center));
        iv_wallet_reddot.setVisibility(View.INVISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAvatarEvent(AvatarEvent avatarEvent) {
        if (!"0".equals(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE))) {
            ImageLoader.getInstance().displayCricleImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE), imageViewHead);
            MyApplication.getInstance().options.uiCustomization.rightAvatar = MyApplication.getInstance().getImageUrl() + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PICTURE);
        } else {
            ImageLoader.getInstance().displayCricleImage(getApplicationContext(), R.drawable.icon_head, imageViewHead);
            MyApplication.getInstance().options.uiCustomization.rightAvatar = "android.resource://" + mContext.getPackageName() + "/" + R.drawable.icon_head;
        }
        centerUsername.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.USER_NICK));

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDrawerEvent(DrawerEvent drawerEvent) {
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) == null) {//未登录
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        } else {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }
    }

    //配置数据获取到后
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConfigEvent(ConfigEvent configEvent) {
        //侧栏畅行卡是否显示
        if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.CHANG_XING_CARD, 0) == 1) {
            imageView_main_card.setVisibility(View.VISIBLE);
            imageView_card.setVisibility(View.VISIBLE);
        } else {
            imageView_main_card.setVisibility(View.GONE);
            imageView_card.setVisibility(View.GONE);
        }
        //控制顶部显示
        mainTitleTvGx.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.TOP_BANNER_TEXT0) + "");
        mainTitleTvSx.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.TOP_BANNER_TEXT1) + "");
        mainTitleTvTan.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.TOP_BANNER_TEXT2) + "");
        if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.SHARE_CAR, 0) == 1) {
            mainTitleTvGx.setVisibility(View.VISIBLE);
        } else {
            mainTitleTvGx.setVisibility(View.GONE);
        }
        if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.EXCLUSIVE_CAR, 0) == 1) {
            mainTitleTvSx.setVisibility(View.VISIBLE);
        } else {
            mainTitleTvSx.setVisibility(View.GONE);
        }
        if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.SHOT_CAR, 0) == 1) {
            mainTitleTvTan.setVisibility(View.VISIBLE);
        } else {
            mainTitleTvTan.setVisibility(View.GONE);
        }
    }

    private void initBoundObservable(boolean showSplash) {
        //收到定位成功后，开始获取围栏，获取后
        Observable<Boolean> boundObservable = RxBus.getInstance()
                .toObservable(OnLocationDoneEvent.class)
                .flatMap(new Function<OnLocationDoneEvent, ObservableSource<CityBoundBean>>() {
                    @Override
                    public ObservableSource<CityBoundBean> apply(OnLocationDoneEvent onLocationDoneEvent) throws Exception {
                        String boundVersion = SPUtils.getInstance(mContext).getStringValue(SPKey.BOUNDS_VERSION);
                        if (!SDCardUtils.isFileExist(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "boundCache.txt")) {
                            boundVersion = null;
                        }
                        return RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4)
                                .getFenceList(MyApplication.getInstance().getRequestFieldMap(), boundVersion)
                                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
                    }
                })
                .flatMap((Function<CityBoundBean, ObservableSource<Boolean>>) cityBoundBean -> {
                    Logger.d("bounds", "定位成功后获取到围栏数据");
                    if (cityBoundBean.getStatus() == 200 && cityBoundBean.getAttachment().getIsNewest() == 0) {//需要跟新数据
                        Logger.d("bounds", "使用网络围栏数据");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.BOUNDS_VERSION, cityBoundBean.getAttachment().getVersion());
                        SDCardUtils.removeFileFromSDCard(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "boundCache.txt");
                        SDCardUtils.saveFileToSDCardPrivateCacheDir(new Gson().toJson(cityBoundBean).getBytes(), "boundCache.txt", mContext);

                        if (overlayUtils != null && cityBoundBean.getAttachment() != null && cityBoundBean.getAttachment().getFenceArea() != null && cityBoundBean.getAttachment().getFenceArea().size() > 0) {
                            Logger.d("bounds", "开始画围栏" + cityBoundBean.getAttachment().getFenceArea().size());
                            overlayUtils.allBounds = cityBoundBean.getAttachment().getFenceArea();
                            overlayUtils.addBounds();
                            Logger.d("bounds", "画围栏完毕");
                            return Observable.create(emitter -> {
                                emitter.onNext(true);//有围栏发送true
                                emitter.onComplete();
                            });
                        }
                    } else if (cityBoundBean.getAttachment().getIsNewest() == 1) {//不需要更新数据,直接从本地读取
                        Logger.d("bounds", "从本地获取围栏数据， 状态码为" + cityBoundBean.getStatus());
                        String boundCache = SDCardUtils.loadFileFromSDCardToStirng(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "boundCache.txt");
                        if (!TextUtils.isEmpty(boundCache)) {
                            cityBoundBean = new Gson().fromJson(boundCache, CityBoundBean.class);
                            if (overlayUtils != null && cityBoundBean.getAttachment() != null && cityBoundBean.getAttachment().getFenceArea() != null && cityBoundBean.getAttachment().getFenceArea().size() > 0) {
                                overlayUtils.allBounds = cityBoundBean.getAttachment().getFenceArea();
                                overlayUtils.addBounds();
                                return Observable.create(emitter -> {
                                    emitter.onNext(true);//有围栏发送true
                                    emitter.onComplete();
                                });
                            }
                        }
                    }
                    return Observable.create(emitter -> {
                        emitter.onNext(false);//没有围栏发送false
                        emitter.onComplete();
                    });
                }).onErrorResumeNext(throwable -> {
                    throwable.printStackTrace();
                    Logger.d("bounds", "获取网络围栏错误，从本地获取围栏数据");
                    String boundCache = SDCardUtils.loadFileFromSDCardToStirng(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "boundCache.txt");
                    if (boundCache != null && overlayUtils != null) {
                        CityBoundBean cityBoundBean = new Gson().fromJson(boundCache, CityBoundBean.class);
                        overlayUtils.allBounds = cityBoundBean.getAttachment().getFenceArea();
                        overlayUtils.addBounds();
                        return Observable.create(emitter -> {
                            emitter.onNext(true);//有围栏发送true
                            emitter.onComplete();
                        });
                    } else {
                        return Observable.create(emitter -> {
                            emitter.onNext(false);//没有围栏发送false
                            emitter.onComplete();
                        });
                    }

                });

        Observable.zip(RxBus.getInstance().toObservable(OnSplashFadeEvent.class), RxBus.getInstance().toObservable(OnLocationDoneEvent.class), boundObservable, new Function3<OnSplashFadeEvent, OnLocationDoneEvent, Boolean, Boolean>() {
            @Override
            public Boolean apply(OnSplashFadeEvent onSplashFadeEvent, OnLocationDoneEvent onLocationDoneEvent, Boolean hasBound) throws Exception {
                return hasBound;
            }
        }).flatMap(new Function<Boolean, ObservableSource<Boolean>>() {
            @Override
            public ObservableSource<Boolean> apply(Boolean hasBound) throws Exception {
                return Observable.just(true).delay(hasBound ? 1500 : 0, TimeUnit.MILLISECONDS);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        compositeDisposable.clear();
                        Logger.d("bounds", "围栏展示完毕，开始缩放");
                        splash.setVisibility(View.GONE);
                        mapStatusUtils.animateMove(curPosition, 17, 1500, 0);

                        //获取初始化数据
                        getInitData();
                        //获取弹窗海报
                        getNewPost();
                        //检查未完成订单
                        if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) != null) {  //已登录
                            hasExistingTravel(); //已登录时获取进行中的行程
                            getParksAndCarsByPages(false, true);
                            checkPeccancy();
                        } else {//未登录
                            isLoadingDone = true;
                            dismissLoadingDialog();
                        }
                        initLocationService();
                    }

                    @Override
                    public void onError(Throwable e) {
                        splash.setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                        splash.setVisibility(View.GONE);
                    }
                });

        //如果未登录，splash消失后跳转登录，登录后回到主页面，开始定位
        //已登录，直接开始定位
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) == null) {
            RxBus.getInstance().toObservable(OnSplashFadeEvent.class).subscribe(new Observer<OnSplashFadeEvent>() {
                @Override
                public void onSubscribe(Disposable d) {
                    compositeDisposable.add(d);
                }

                @Override
                public void onNext(OnSplashFadeEvent onSplashFadeEvent) {
                    Intent intent = new Intent();
                    intent.setClass(mContext, LoginActivity.class);
                    startActivity(intent);
                    compositeDisposable.clear();
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

        } else {
            Logger.i("bounds", "已登录开始定位");
            startLocation();
        }

        if (showSplash) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(splash, "alpha", 1, 0.3F, 0);
            animator.setDuration(500);
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    //splash消失后发送通知
                    RxBus.getInstance().post(new OnSplashFadeEvent(true));
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //splash开始消失
                    animator.start();
                }
            }, 1800);
        } else {
            RxBus.getInstance().post(new OnSplashFadeEvent(true));
        }
    }

    private GetFirstCarEvent getFirstCarEventCreated;

    private void initNearestCarObservable() {
        Observable.zip(RxBus.getInstance().toObservable(GetFirstCarEvent.class), RxBus.getInstance().toObservable(GetUnFinishedEvent.class), (getFirstCarEvent, getUnFinishedEvent) -> {
            getFirstCarEvent.isHaveorder = getUnFinishedEvent.isHaveorder;
            getFirstCarEvent.orderId = getUnFinishedEvent.orderId;
            getFirstCarEvent.rentType = getUnFinishedEvent.rentType;
            return getFirstCarEvent;
        }).subscribe(new Observer<GetFirstCarEvent>() {
            @Override
            public void onSubscribe(Disposable d) {
                //compositeDisposable.add(d);
            }

            @Override
            public void onNext(GetFirstCarEvent getFirstCarEvent) {
                Logger.d("CarLog", "发送NearestCar日志");
                ParseApiStore.getInstance().commitLaunchLog(getFirstCarEvent.isHaveorder, getFirstCarEvent.carLat, getFirstCarEvent.carLng, getFirstCarEvent.carId);
                //附近有车，提示优惠券倒计时
                getFirstCarEventCreated = getFirstCarEvent;
                getCouponCountDown(getFirstCarEvent);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getCouponCountDown(GetFirstCarEvent getFirstCarEvent) {

        if (getFirstCarEvent == null || getFirstCarEvent.carId == null)
            return;
        int distance = (int) DistanceUtil.getDistance(curPosition, new LatLng(getFirstCarEvent.carLat, getFirstCarEvent.carLng));

        try {
            Map<String, String> requestFieldMap = MyApplication.getInstance().getRequestFieldMap();
            Type typeParseMapOne = new TypeToken<Map<String, String>>() {
            }.getType();
            JSONObject bodyJson = new JSONObject(new Gson().toJson(requestFieldMap, typeParseMapOne));
            bodyJson.put("userLat", curPosition.latitude);
            bodyJson.put("userLng", curPosition.longitude);
            bodyJson.put("carid", Integer.parseInt(getFirstCarEvent.carId));
            bodyJson.put("orderId", Integer.parseInt(getFirstCarEvent.orderId));
            bodyJson.put("unFinishOrder", getFirstCarEvent.isHaveorder);
            bodyJson.put("rentType", getFirstCarEvent.rentType);
            bodyJson.put("carLng", getFirstCarEvent.carLng);
            bodyJson.put("carLat", getFirstCarEvent.carLat);
            bodyJson.put("range", distance);
            bodyJson.put("userName", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_NICK));
            bodyJson.put("phoneNum", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM));

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
            RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getCouponCountDown(body)
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<CouponCountDownBean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(CouponCountDownBean couponCountDownBean) {
                            handleCouponCountDown(couponCountDownBean);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private Disposable countDownDisposable;

    private void handleCouponCountDown(CouponCountDownBean couponCountDownBean) {
        Logger.d("couponDown", "step1");
        if (couponCountDownBean.getMsg_code() == 200 && couponCountDownBean.getAttachment().getStatus() == 1) {
            Logger.d("couponDown", "step2");
            couponCountdown = findViewById(R.id.coupon_countdown);
            couponCountdown.initTime(mContext, couponCountDownBean);

            //创建倒计时，并显示倒计时
            long count = couponCountDownBean.getAttachment().getRemainingTime() + 1;
            CountDownEvent countDownEvent = new CountDownEvent(0);
            if (countDownDisposable != null && !countDownDisposable.isDisposed()) {
                countDownDisposable.dispose();
            }
            countDownDisposable = Observable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            long remain = count - aLong - 1;
                            Logger.d("couponDown", remain + "");
                            if (remain > 0) {
                                couponCountdown.update(remain);
                            } else {
                                couponCountdown.stop();
                            }

                            RxBus.getInstance().post(countDownEvent.setCount(remain));
                        }
                    });
            Logger.d("couponDown", "step show1");
            if (couponCountDownBean.getAttachment().getPop_up() == 1) {
                Logger.d("couponDown", "step show");

                couponCountdown.popPost(mContext, couponCountDownBean);
            }

            RxBus.getInstance().toObservable(CountDownCloseEvent.class).subscribe(new Consumer<CountDownCloseEvent>() {
                @Override
                public void accept(CountDownCloseEvent countDownCloseEvent) throws Exception {
                    if (couponCountdown != null) {
                        if (countDownDisposable != null && !countDownDisposable.isDisposed()) {
                            countDownDisposable.dispose();
                        }
                        couponCountdown.setVisible(View.GONE);
                    }
                }
            });
        }
    }


    //splash获取动态权限
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            permissionLists.add(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            permissionLists.add(Manifest.permission.CAMERA);
            permissionLists.add(Manifest.permission.READ_PHONE_STATE);
            Logger.i("有拒绝的权限");
            ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUEST_CODE);
        } else {
            initBoundObservable(true);
            initNearestCarObservable();
        }

    }


    //主页面处理权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        initBoundObservable(true);
                        initNearestCarObservable();
                    } else {
                        final DialogTwoButton dialogButton = new DialogTwoButton(mContext);
                        dialogButton.setTitle("定位权限已关闭");
                        dialogButton.setMessage("您需要开启定位权限，才可以查看车辆情况，请到设置的权限管理中开启【大道用的】定位权限。");
                        dialogButton.setCancelable(false);
                        dialogButton.setCanceledOnTouchOutside(false);
                        if (Build.MANUFACTURER.equals("vivo")) {//针对vivo手机，vivo手机未使用原生动态权限的检查
                            dialogButton.setYesOnclickListener("确定", () -> {
                                dialogButton.dismiss();
                            });
                        } else {
                            dialogButton.setYesOnclickListener("开启", () -> {
                                getPermissions();
                                dialogButton.dismiss();
                            });
                        }
                        dialogButton.setNoOnclickListener("取消", () -> {
                            dialogButton.dismiss();
                        });
                        dialogQueue.showDialog(dialogButton);
                    }
                    break;
                }
            }
        }
    }

    //提示打开定位服务
    private void initLocationService() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断是否开启了GPS，如果没有则开启
        if ((locationManager != null) && (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))) {
            final DialogTwoButton inCarDialog = new DialogTwoButton(this);
            inCarDialog.setTitle("GPS定位已关闭");
            inCarDialog.setMessage(getString(R.string.LocationServiceRemind));
            inCarDialog.setYesOnclickListener("设置", () -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                inCarDialog.dismiss();
            });
            inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
            inCarDialog.setCanceledOnTouchOutside(true);
            inCarDialog.setCancelable(true);
            dialogQueue.showDialog(inCarDialog);
        }

    }


    //初始化地图
    public void initMap() {
        mapView = (MapView) findViewById(R.id.map_mainActivity);
        mapView.showZoomControls(false);
        //MapView.setMapCustomEnable(true);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        if (mBaiduMap == null) {
            mBaiduMap = mapView.getMap();
            overlayUtils = new OverlayUtils(mContext, mBaiduMap);
            // 开启定位图层
            mBaiduMap.setBuildingsEnabled(false);
            mBaiduMap.setMyLocationEnabled(true);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true,
                    BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation), 0x00000000, 0x00000000));
            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);

            mapStatusUtils = new MapStatusUtils(mContext, mBaiduMap);
            mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    backPress(false);
                }

                @Override
                public boolean onMapPoiClick(MapPoi mapPoi) {
                    return false;
                }
            });


            mBaiduMap.setOnMarkerClickListener(marker -> {
                //获取附加在marker中的数据
                Bundle markerInfoBundle = marker.getExtraInfo();
                if (markerInfoBundle != null) {
                    String carId = markerInfoBundle.getString("carId");
                    //根据parkId显示网点的详情，或者只显示一个车辆的详情
                    if (markerInfoBundle.getString("markerType").equals(MarkerOverlay.MarkerType.CAR.name())) {
                        if (StateType.loadState == StateType.LoadMarkerState.LOADING) {
                            return true;
                        }
                        //点击车辆,所有图标的
                        overlayUtils.getNearTwenty(curPosition, (errorCode, nearCarList) -> {
                            StateType.setCurState(PAGER_ONE_AND_NEAR);
                            overlayUtils.clearMap();
                            List<ContentBean> nearAndOneCarList = new ArrayList<>(nearCarList);
                            overlayUtils.markerOverlay.addNearTwentyMarker(nearAndOneCarList);//附近20辆Marker添加到地图上
                            nearAndOneCarList.add(0, overlayUtils.allCarList.get(carId));//把点选的这一辆添加到附近车辆中
                            dismissLoadingDialog();
                            layout_find_car.setVisibility(View.GONE);
                            findCarFee.setVisibility(View.GONE);
                            tabSwitchView.setDefault();
                            carsPagerAdapter = new CarsPagerAdapter(mContext, nearAndOneCarList, overlayUtils.markerOverlay.picMap);
                            if (nearAndOneCarList.size() == 1) {
                                vpCar.canLoop(false);
                            } else {
                                vpCar.canLoop(true);
                            }
                            vpCar.setPageMargin((int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
                            vpCar.setAdapter(carsPagerAdapter);
                            LatLng carPosition = new LatLng((carsPagerAdapter.getItem(0)).getLatitude(), (carsPagerAdapter.getItem(0)).getLongitude());
                            controlLayout(layout_car_pager, true, carPosition);
                            //overlayUtils.addBounds();
                        });

                    } else if (markerInfoBundle.getString("markerType").equals(MarkerOverlay.MarkerType.NEAR_CAR.name())) {
                        //点击的是20辆的车辆,滑动至对应的卡片
                        //根据parkId循环找出对应pagerAdapter的item
                        for (int i = 0; i < carsPagerAdapter.getCount(); i++) {
                            if (carsPagerAdapter.getItem(i) != null) {
                                if (carId.equals((carsPagerAdapter.getItem(i)).getId())) {
                                    vpCar.setCurrentItem(i, true);
                                    break;
                                }
                            }
                        }
                    } else if (markerInfoBundle.getString("markerType").equals(MarkerOverlay.MarkerType.CITY.name())
                            && markerInfoBundle.getString("cityCode").equals(MyApplication.getInstance().getAreaCode())) {
                        mapStatusUtils.animateMove(curPosition, 17, 600, 0);
                    }
                }
                return true;
            });
            mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus) {
                }

                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
                }

                @Override
                public void onMapStatusChange(MapStatus mapStatus) {

                }

                @Override
                public void onMapStatusChangeFinish(MapStatus mapStatus) {

                    if (mapStatus.zoom < 10 && StateType.isEqualsCurStates(StateType.State.DEFAULT)) {
                        StateType.setCurState(StateType.State.SHOW_CITY);
                        overlayUtils.clearMap();
                        overlayUtils.addCitiesMarkerToMap();
                    } else if (mapStatus.zoom >= 10 && StateType.isEqualsCurStates(StateType.State.SHOW_CITY)) {
                        StateType.setCurState(StateType.State.DEFAULT);
                        overlayUtils.clearMap();
                        getParksAndCarsByPages(false, true);
                    }
                    overlayUtils.addBounds();
                }
            });
        }
    }

    @OnClick({R.id.main_title_tv_gx, R.id.main_title_tv_sx, R.id.main_title_tv_tan, R.id.layout_send_tv_service, R.id.layout_tv_scan_license, R.id.imageView_center, R.id.imageView_locate, R.id.use_car, R.id.car_detail_rent, R.id.find_car_cancel_order,
            R.id.find_car_fee_tip, R.id.info_image_head, R.id.myInfo_route, R.id.myInfo_wallet, R.id.myInfo_service,
            R.id.myInfo_guide, R.id.myInfo_invite, R.id.rl_setting, R.id.rl_weizhang, R.id.rl_park_fee, R.id.debug_entry, R.id.contact_deliver, R.id.find_car_current, R.id.myInfo_oil, R.id.imageView_card, R.id.imageView_main_card})
    public void onViewClicked(View view) {
        if (AntiShake.check(view.getId())) return;    //判断是否多次点击
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.imageView_center:
                if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) == null) {//未登录
                    intent.setClass(mContext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    drawer.openDrawer(Gravity.START);
                }
                break;
            case R.id.imageView_locate:
                if (curPosition != null) {
                    if (StateType.isEqualsCurStates(StateType.State.CAR_FIND) || StateType.isEqualsCurStates(StateType.State.SHOW_PAGER)) {
                        mapStatusUtils.animateMove(curPosition, 17, 600);
                    } else {
                        mapStatusUtils.animateMove(curPosition, 17, 600, 0);
                    }

                } else {
                    isFirstLocationError = true;
                    startLocation();
                    //ToastUtils.makeText(mContext, "正在定位...", ToastUtils.LENGTH_SHORT).show();
                }
                break;
            //选车
            case R.id.use_car:
                if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) != null) {  //登录状态
                    if (curPosition != null) {
                        if (SPUtils.getInstance(mContext).getIntValue(SPKey.IS_CITY_OPEN) == 1) {
                            if (StateType.loadState != StateType.LoadMarkerState.LOADING)
                                getNearTwenty(overlayUtils.markerOverlay.hasCityMarker);
                        } else {
                            noService();
                        }
                    } else {
                        isFirstLocationError = true;
                        startLocation();
                    }
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
                break;
            //立即租用
            case R.id.car_detail_rent:
                canRentCar();
                break;
            //取消订单按钮
            case R.id.find_car_cancel_order:
                showCancelOrder(OrderRepository.cancelCount);
                break;
            //停车费补偿提示
            case R.id.find_car_fee_tip:
                intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_input_fee_guide));
                SPUtils.getInstance(mContext).putIntValue(SPKey.PARKFEE_CLICK, 1);
                findCarFee.setBackground(getResources().getDrawable(R.drawable.park_fee_tips_white));
                startActivity(intent);
                break;
            case R.id.info_image_head:
                intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_personal_center));
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "个人中心");
                startActivity(intent);
                break;
            case R.id.myInfo_wallet:
                String cachekey = SPUtils.getInstance(mContext).getStringValue(SPKey.CACHE_KEY);
                SPUtils.getInstance(mContext).putIntValue(cachekey, 1);
                imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center));
                iv_wallet_reddot.setVisibility(View.INVISIBLE);
                Intent intent_wallet = new Intent(mContext, WebViewActivity.class);
                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的钱包");
                CookieManager cookieManager2 = CookieManager.getInstance();
                cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "isExist=" + SPUtils.getInstance(mContext).getIntValue(SPKey.DOT_ISEXITE));
                cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "RushedSendPicture=" + SPUtils.getInstance(mContext).getStringValue(SPKey.WALLET_PICTURE));
                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet));
                startActivity(intent_wallet);
                break;
            case R.id.myInfo_oil:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的油箱");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_gasoline));
                startActivity(intent);
                break;
            case R.id.rl_setting:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "设置");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_setting));
                startActivity(intent);
                break;
            case R.id.myInfo_route:
                if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.WEB_ORDER_HISTORY, 1) == 0) {
                    intent.setClass(mContext, TravelRecordActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(mContext, WebViewActivity.class);
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的订单");
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_order_list));
                    startActivity(intent);
                }

                break;
            case R.id.myInfo_invite:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "邀请好友");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_share_third));
                startActivity(intent);
                break;
            case R.id.myInfo_guide:
                String title = "用户指南";
                Intent intent_register = new Intent(mContext, WebViewActivity.class);
                intent_register.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, title);
                intent_register.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_guide) + "?appVersion=" + MyApplication.getInstance().getAppVersion());
                startActivity(intent_register);
                break;
            case R.id.myInfo_service:
               /* if (Unicorn.isServiceAvailable()) {
                    ConsultService consultService = new ConsultService(mContext);
                    consultService.consultService(mContext, "", "", "", null);
                } else {
                    intent.setClass(mContext, ContactServiceActivity.class);
                    startActivity(intent);
                }*/
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "大道客服");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.HTML_QIMO + "userId=" + ((MyApplication) getApplication()).getUid() + "&nickName=" + centerUsername.getText().toString() + "&phone=" + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM));
                startActivity(intent);
                break;
            case R.id.rl_weizhang:
                if (!NetUtils.isNetworkAvailable(mContext)) {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    return;
                }
                notifyPeccancy();
                imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center));
                iv_weizhang_reddot.setVisibility(View.INVISIBLE);
                Intent intent_weizhang = new Intent(mContext, WebViewActivity.class);
                intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "违章查询");
                intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_break_rules));
                startActivity(intent_weizhang);
                break;

            case R.id.rl_park_fee:
                Intent intent_parkFee = new Intent(mContext, WebViewActivity.class);
                intent_parkFee.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "停车费查询");
                intent_parkFee.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_parkingFee_list));
                startActivity(intent_parkFee);
                break;
            case R.id.debug_entry:
                intent.setClass(mContext, DebugModeActivity.class);
                startActivity(intent);
                break;
            case R.id.contact_deliver:
                getTel();
                break;
            case R.id.find_car_current:
                currentFee();
                break;
            case R.id.imageView_card:
            case R.id.imageView_main_card:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的畅行卡");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_discountCardValidRecord));
                startActivity(intent);
            case R.id.main_title_tv_gx:
                mainTitleTvGx.setTextSize(14);
                mainTitleTvGx.setTextColor(Color.parseColor("#2A6CFF"));
                mainTitleTvSx.setTextSize(12);
                mainTitleTvSx.setTextColor(Color.parseColor("#999999"));
                mainTitleTvTan.setTextSize(12);
                mainTitleTvTan.setTextColor(Color.parseColor("#999999"));
                break;
            case R.id.main_title_tv_sx:
                mainTitleTvSx.setTextSize(14);
                mainTitleTvSx.setTextColor(Color.parseColor("#2A6CFF"));
                mainTitleTvGx.setTextSize(12);
                mainTitleTvGx.setTextColor(Color.parseColor("#999999"));
                mainTitleTvTan.setTextSize(12);
                mainTitleTvTan.setTextColor(Color.parseColor("#999999"));
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "私享车");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_exclusiveCar));
                startActivity(intent);
                break;
            case R.id.main_title_tv_tan:
                mainTitleTvTan.setTextSize(14);
                mainTitleTvTan.setTextColor(Color.parseColor("#2A6CFF"));
                mainTitleTvGx.setTextSize(12);
                mainTitleTvGx.setTextColor(Color.parseColor("#999999"));
                mainTitleTvSx.setTextSize(12);
                mainTitleTvSx.setTextColor(Color.parseColor("#999999"));
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "弹个车");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.shotACarUrl));
                startActivity(intent);
                break;
            case R.id.layout_send_tv_service:
                intent.setClass(mContext, DeliverCarActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_tv_scan_license:
                startActivity(new Intent(MainActivity.this, RecogCarPlateActivity.class));
                break;
        }
    }

    //当前订单费用
    public void currentFee() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getCurrentFee(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId).enqueue(new Callback<CurrentFeeBean>() {
            @Override
            public void onResponse(Call<CurrentFeeBean> call, Response<CurrentFeeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Logger.d("driving cur fee", new Gson().toJson(response.body()));
                    dismissLoadingDialog();
                    if (response.body().getStatus() == 200 && response.body().getAttachment() != null) {
                        final CarCurrentParkFeeDialog dialog = new CarCurrentParkFeeDialog(mContext);
                        dialog.setData(response.body().getAttachment().getList());
                        dialog.show();

                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CurrentFeeBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void getTel() {
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("orderId", OrderRepository.orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 5).getSendTel(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SendTelBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(SendTelBean sendTelBean) {
                        if (sendTelBean.getStatus() == 200) {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + sendTelBean.getAttachment().getPhone()));
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + SPUtils.getInstance(mContext).getStringValue(SPKey.HOT_LINE)));
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    private int lastPosition = 0;

    //初始化网点车辆弹出布局,从列表选择，一键选车，点击图标弹出的布局
    private void initCarPagerLayout() {
        layout_car_pager = (RelativeLayout) findViewById(R.id.layout_car_pager);
        abatementCheckBox = findViewById(R.id.checkbox);
        txInsure = (TextView) findViewById(R.id.car_detail_insure_tv);
        TextView car_detail_rent = findViewById(R.id.car_detail_rent);
        vpCar = (LoopViewPager) findViewById(R.id.vp_car);
        layout_car_pager.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        MyRelativeLayout pushDownView = findViewById(R.id.layout_push_down);
        pushDownView.setOnPullLister(() -> onBackPressed());
        tabSwitchView = findViewById(R.id.tab_switch_view);
        tabSwitchView.setOnTabChangeListener(new TabSwitchView.OnTabChangeListener() {
            @Override
            public void onTabChange(int selectedIndex) {
                Logger.d("tabChange", selectedIndex + "");
                if (selectedIndex == 0) {
                    car_detail_rent.setTextSize(COMPLEX_UNIT_DIP, 18);
                    car_detail_rent.setText("立即预订");
                    RxBus.getInstance().post(new TabChangeEvent(0));
                    txInsure.setText(new DecimalFormat("不计免赔(#.##元/单)").format(carsPagerAdapter.getItem(lastPosition).getAbatement()));
                } else if (selectedIndex == 1) {
                    car_detail_rent.setTextSize(COMPLEX_UNIT_DIP, 15);
                    car_detail_rent.setText("预订");
                    txInsure.setText(new DecimalFormat("不计免赔(#.##元/小时)").format(900));

                    RxBus.getInstance().post(new TabChangeEvent(1));
                } else if (selectedIndex == 2) {
                    car_detail_rent.setTextSize(COMPLEX_UNIT_DIP, 15);
                    car_detail_rent.setText("预订");
                    txInsure.setText(new DecimalFormat("不计免赔(#.##元/天)").format(carsPagerAdapter.getItem(lastPosition).getDayAbatement()));
                    RxBus.getInstance().post(new TabChangeEvent(1));
                }
            }

            @Override
            public void onHoursChosen(String selectedId) {

            }

            @Override
            public void onTimeChosen(String timeMills) {
                getRentDuration(timeMills);
            }
        });


        vpCar.addOnPageChangeListener(new LoopViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Logger.d("pagerPosition", position + "  pagerPositionOut");
                compositeDisposable.clear();
                if (StateType.isEqualsCurStates(PAGER_ONE_AND_NEAR) || StateType.isEqualsCurStates(PAGER_NEAR)) {
                    //1+20辆时第一个page滑出后，下次滑回不再出现这个page，并且滑出第一个后移除1+20的第一个marker
                    if (StateType.isEqualsCurStates(PAGER_ONE_AND_NEAR)) {
                        Logger.d("pagerPosition", position + "  pagerPosition");

                        int offDir = 0;
                        if (lastPosition == 1) {
                            //左移
                            offDir = 1;
                        }
                        lastPosition = position;

                        //1+20辆时，第一个page滑出后，下次滑回不再出现这个page
                        if (position == 0 && carsPagerAdapter.isSkip) {//isSkip:position==0时可能是第一次进入，也可能是滑回了第一个，需要标识区分。
                            if (offDir == 0) {
                                vpCar.setCurrentItem(1, false);
                            } else {
                                vpCar.setCurrentItem(carsPagerAdapter.getCount() - 1, false);
                            }
                            return;
                        }
                        carsPagerAdapter.isSkip = true;
                        // overlayUtils.markerOverlay.nearTwentyMarkerList.get(0).remove();//移除1+20的第一个marker

                    }

                    if (StateType.isEqualsCurStates(PAGER_NEAR)) {
                        lastPosition = position;
                    }

                    //CarMergeInfoBean carMergeInfo = new CarMergeInfoBean();
                    if (carsPagerAdapter.getItem(position) != null) {
                        //获得carLIst中找到当前选中车的数据
                        ContentBean carBean = overlayUtils.allCarList.get(carsPagerAdapter.getItem(position).getId());
                        Logger.d("abaa", carBean.getHideLicenseTag() + "    " + carBean.getAbatement() + "    " + carBean.getDayAbatement());

                        mapStatusUtils.animateMove(new LatLng(carBean.getLatitude(), carBean.getLongitude()), -1, 500);
                        if (tabSwitchView.getSelected() == 0) {
                            txInsure.setText(new DecimalFormat("不计免赔(#.##元/单)").format(carBean.getAbatement()));
                            car_detail_rent.setText("立即预订");
                        } else {
                            txInsure.setText(new DecimalFormat("不计免赔(#.##元/天)").format(carBean.getDayAbatement()));
                            car_detail_rent.setText("选择日租天数");
                        }
                        //替换选中的图标

                        if (position == 0) {
                            overlayUtils.addSelectedCar(carBean, overlayUtils.markerOverlay.nearTwentyMarkerList.containsKey(carBean.getId()));
                        } else {
                            overlayUtils.addSelectedCar(carBean, true);
                        }


                        getReturnComment(carBean);
                    }

                }
            }


            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void getRentDuration(String timeMills) {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("rentType", "3");
            bodyJson.put("rentEndTime", timeMills);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 5).getRentDuration(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RentDurationBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RentDurationBean result) {
                        dismissLoadingDialog();
                        if (result.getStatus() == 200) {
                            if (tabSwitchView != null) {
                                tabSwitchView.setDayRentDuration(timeMills, result.getAttachment().getPreRentTime());
                            }
                        } else {
                            ToastUtils.makeText(mContext, result.getMessage(), ToastUtils.LENGTH_SHORT).show();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void getReturnComment(ContentBean carBean) {

        //获取金豆车信息
        Observable<GoldCarOneBean> goldOneCarObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getGoldOneCar(MyApplication.getInstance().getRequestFieldMap(), carBean.getId())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<GoldCarOneBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象
                            emitter.onNext(new GoldCarOneBean());
                            emitter.onComplete();
                        }));

        //还车备注信息
        Observable<ReturnCarCommentBean> returnCarCommentObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getReturnCarComment("epimetheus/v1/rcc/" + carBean.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<ReturnCarCommentBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象，以便后续兼容错误处理
                            emitter.onNext(new ReturnCarCommentBean());
                            emitter.onComplete();
                        }));


        //组合各个接口的数据并更新车信息
        Observable.zip(goldOneCarObservable, returnCarCommentObservable, (goldCarOneBean, returnCarCommentBean) -> {
            if (goldCarOneBean != null && goldCarOneBean.getMsg_code() == 200 && goldCarOneBean.getAttachment() != null) {
                carBean.setGoldCarStatus(goldCarOneBean.getAttachment().getCar_status());
                carBean.setGoldCarType(goldCarOneBean.getAttachment().getGold_car_type());
                carBean.setGoldCarMinutes(goldCarOneBean.getAttachment().getShort_minutes());
                if (goldCarOneBean.getAttachment().getCar_status() == 1) {//查找金豆车图片
                    carBean.setGoldPic(overlayUtils.goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("half_gold_icon"));
                } else if (goldCarOneBean.getAttachment().getCar_status() == 2) {
                    carBean.setGoldPic(overlayUtils.goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("gold_icon"));
                }
            }

            if (returnCarCommentBean != null && returnCarCommentBean.getMsg_code() == 200 && returnCarCommentBean.getAttachment() != null) {
                carBean.setImgs(returnCarCommentBean.getAttachment().getComment().getImgs());
                carBean.setOnGround(returnCarCommentBean.getAttachment().getComment().getOnGround());
                carBean.setRemarkMsg(returnCarCommentBean.getAttachment().getComment().getRemarkMsg());
            }
            return carBean;
        }).onErrorResumeNext((Function<Throwable, ObservableSource<ContentBean>>) throwable ->
                Observable.create(emitter -> {//接口错误返回一个空对象，以便后续兼容错误处理
                    emitter.onNext(carBean);
                    emitter.onComplete();
                }))
                .subscribe(new Observer<ContentBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(ContentBean c) {
                        compositeDisposable.clear();
                        overlayUtils.showCarLocationInfoWindow(carBean);
                        overlayUtils.updateOneMarkerInfo(carBean);//更新已保存的车图标

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.d("returncommnet", "获取了还车备注/金豆车错误");
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void canRentCar() {
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) == null) {
            startActivity(new Intent(mContext, LoginActivity.class));
            return;
        }
        if (SPUtils.getInstance(mContext).getIntValue(SPKey.IS_CITY_OPEN) != 1) {
            noService();
            return;
        }

        if (tabSwitchView.getSelected() == 1 && !tabSwitchView.isChosenTime()) {
            ToastUtils.makeText(mContext, "请选择用车时间", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        if (tabSwitchView.getSelected() == 2 && !tabSwitchView.isChosenTime()) {
            ToastUtils.makeText(mContext, "请选择还车时间", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        tipCheckAbatement();

    }

    private void tipCheckAbatement() {
        if (abatementCheckBox.isChecked()) {//勾选了不计免赔
            checkOrder();
        } else {//未勾选
            ConfirmAbatementDialog confirmAbatementDialog = new ConfirmAbatementDialog(mContext);
            confirmAbatementDialog.setData(txInsure.getText().toString().substring(4));
            confirmAbatementDialog.setOnCheckResultListener(new ConfirmAbatementDialog.OnCheckResultListener() {
                @Override
                public void onCheckDefault() {
                    SPUtils.getInstance(mContext).putStringValue(SPKey.ABATEMENT_CHECK, "1");
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    checkOrder();

                }

                @Override
                public void onCheckNo() {
                    abatementCheckBox.setChecked(false);
                    confirmAbatementDialog.dismiss();
                    checkOrder();
                }

                @Override
                public void onCheckOnce() {
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    checkOrder();

                }

                @Override
                public void onCheckOk() {
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    checkOrder();
                }
            });
            confirmAbatementDialog.show();

        }

    }

    private void checkOrder() {
        showLoadingDialog();
        getUnOrder(new OrderRepository.GetUnfinishedOrderDone() {
            @Override
            public void onHaveOrder(@NotNull UnFinishedOrderBean data) {
                dismissLoadingDialog();
            }

            @Override
            public void onNoOrder() {
                if (carsPagerAdapter.getItem(vpCar.getCurrentItem()) != null) {
                    //网点外车的详情，数据来自地图所有图标接口
                    OrderRepository.carId = (carsPagerAdapter.getItem(vpCar.getCurrentItem())).getId();
                    String carGrade = (carsPagerAdapter.getItem(vpCar.getCurrentItem())).getGradePic();
                    isInsuranceCheck = abatementCheckBox.isChecked() ? "1" : "2";
                    if (tabSwitchView.getSelected() == 0) {//共享
                        rentCar(isInsuranceCheck, null);
                    } else if (tabSwitchView.getSelected() == 1 || tabSwitchView.getSelected() == 2) {//小日租,日租
                        checkEnduranceMileage(carGrade);//检查续

                    }
                }
            }

            @Override
            public void onError(@NotNull String message) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                Logger.d("netError", "查询进行中订单失败  " + message);
            }
        });
    }


    private void checkEnduranceMileage(String carGrade) {
        showLoadingDialog();
        String rentType = "1";
        if (tabSwitchView.getSelected() == 1) {
            rentType = "5";
        } else if (tabSwitchView.getSelected() == 2) {
            rentType = "2";
        }
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkEnduranceMileage(MyApplication.getInstance().getRequestFieldMap(),
                OrderRepository.carId, abatementCheckBox.isChecked() ? "1" : "2",
                tabSwitchView.getSelected() == 1 || tabSwitchView.getSelected() == 2 ? "1" : null,
                rentType, tabSwitchView.getEndTime(), tabSwitchView.getLittleDaySelectedId())
                .enqueue(new Callback<CommonResultBean>() {
                    @Override
                    public void onResponse(Call<CommonResultBean> call, final Response<CommonResultBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                getDayRentPrice(carGrade, isInsuranceCheck);
                            } else if (response.body().getStatus() == 600) {
                                dismissLoadingDialog();
                                DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
                                dialogTwoButton.setMessage(response.body().getMessage());
                                dialogTwoButton.setNoOnclickListener("取消", () -> dialogTwoButton.dismiss());
                                dialogTwoButton.setYesOnclickListener("继续使用", () -> {
                                    dialogTwoButton.dismiss();
                                    getDayRentPrice(carGrade, isInsuranceCheck);
                                });
                                dialogTwoButton.show();
                            } else if (response.body().getStatus() == 20) {
                                dismissLoadingDialog();
                                SystemToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            } else {
                                dismissLoadingDialog();
                                SystemToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            SystemToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResultBean> call, Throwable t) {
                        dismissLoadingDialog();
                        SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    private void getDayRentPrice(String carGrade, String isAbatement) {
        showLoadingDialog();
        String rentType = "1";
        if (tabSwitchView.getSelected() == 1) {
            rentType = "5";
        } else if (tabSwitchView.getSelected() == 2) {
            rentType = "2";
        }
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getDayRentPrice(MyApplication.getInstance().getRequestFieldMap(),
                OrderRepository.carId, isAbatement, tabSwitchView.getSelected() == 1 || tabSwitchView.getSelected() == 2 ? "1" : null,
                rentType, tabSwitchView.getEndTime(), tabSwitchView.getLittleDaySelectedId())
                .enqueue(new Callback<DayRentPriceBean>() {
                    @Override
                    public void onResponse(Call<DayRentPriceBean> call, final Response<DayRentPriceBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {

                                dismissLoadingDialog();
                                ConfirmDayRentDialog confirmChooseDaysDialog = new ConfirmDayRentDialog(mContext);
                                confirmChooseDaysDialog.setData(response.body().getAttachment());
                                confirmChooseDaysDialog.setCarGrade(carGrade);
                                confirmChooseDaysDialog.setNoOnclickListener(() -> {
                                    confirmChooseDaysDialog.dismiss();
                                });
                                confirmChooseDaysDialog.setYesOnclickListener(type -> {
                                    rentCar(isInsuranceCheck, confirmChooseDaysDialog);
                                });
                                confirmChooseDaysDialog.show();

                            } else if (response.body().getStatus() == 20) {
                                dismissLoadingDialog();
                                SystemToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            } else {
                                dismissLoadingDialog();
                                SystemToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<DayRentPriceBean> call, Throwable t) {
                        dismissLoadingDialog();
                        SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }


    //初始化下单寻车弹出布局
    private void initFindCarLayout() {
        find_car_brandModel = (TextView) findViewById(R.id.find_car_brandModel);
        find_car_qipao = (TextView) findViewById(R.id.find_car_qipao);
        layout_find_car = (LinearLayout) findViewById(R.id.layout_find_car);
        iv_order_car = (ImageView) findViewById(R.id.iv_order_car);
        tx_place_order_plate = (TextView) findViewById(R.id.tx_place_order_plate);
        tx_reserve_order_timer = (TextView) findViewById(R.id.tx_place_order_timer);
        find_car_current = findViewById(R.id.find_car_current);
        find_car_find = (ImageButton) findViewById(R.id.driving_car_find);
        find_car_open = (ImageButton) findViewById(R.id.driving_car_open);
        countDownIndicate = (CountDownIndicate) findViewById(R.id.cd_indicate);
        layout_find_car.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        find_car_begin = findViewById(R.id.find_car_begin);
        //寻车按钮
        find_car_find.setOnClickListener(view -> {
            if (!NetUtils.isNetworkAvailable(mContext)) {
                ToastUtils.makeText(mContext, "网络无法连接", 2000).show();
                return;
            }
            findCar();

        });
        //开门按钮
        find_car_open.setOnClickListener(view -> {
            if (!NetUtils.isNetworkAvailable(mContext)) {
                ToastUtils.makeText(mContext, "网络无法连接", 2000).show();
                return;
            }

            DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
            dialogTwoButton.setTitle("点击开门将开始计费");
            dialogTwoButton.setMessage("是否已找到车辆？");
            dialogTwoButton.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    dialogTwoButton.dismiss();
                }
            });
            dialogTwoButton.setYesOnclickListener("确定", new DialogTwoButton.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    dialogTwoButton.dismiss();
                    //判断账户余额，判断油量
                    checkAccount();
                }
            });
            dialogTwoButton.show();
        });
    }

    private void checkAccount() {
        showLoadingDialog();


        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("orderId", OrderRepository.orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkUserMoney(body)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CheckUserAccountBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CheckUserAccountBean result) {
                        dismissLoadingDialog();
                        if (result.getStatus() == 200) {
                            if (OrderRepository.bookType == 4) {
                                checkOil();
                            } else {
                                rxOpenCarDoorOnlyNet();
                            }
                        } else if (result.getStatus() == 405) {
                            NeedRechargeDialog needRechargeDialog = new NeedRechargeDialog(mContext);
                            needRechargeDialog.setData(result.getAttachment());
                            needRechargeDialog.setNoOnclickListener(needRechargeDialog::dismiss);
                            needRechargeDialog.setYesOnclickListener(() -> {
                                if (OrderRepository.bookType == 4) {
                                    checkOil();
                                } else {
                                    rxOpenCarDoorOnlyNet();
                                }
                            });
                            needRechargeDialog.show();
                        } else {
                            ToastUtils.makeText(mContext, result.getMessage(), ToastUtils.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void checkOil() {
        showLoadingDialog();
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getOilRemain(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReturnOilBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ReturnOilBean returnOilBean) {
                        dismissLoadingDialog();
                        if (returnOilBean.getStatus() == 200) {
                            DialogOneButton oilTipDialog = new DialogOneButton(mContext);
                            oilTipDialog.setMessage("当前油量" + returnOilBean.getAttachment().getCarOil() + "L");
                            oilTipDialog.setYesOnclickListener("知道了", () -> {
                                oilTipDialog.dismiss();
                                rxOpenCarDoorOnlyNet();
                            });
                            oilTipDialog.show();
                        } else {
                            ToastUtils.makeText(mContext, returnOilBean.getMessage(), ToastUtils.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initAppData() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).initApp(MyApplication.getInstance().getRequestFieldMap(), "1")
                .enqueue(new Callback<InitBean>() {
                    @Override
                    public void onResponse(Call<InitBean> call, final Response<InitBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                InitBean.AttachmentBean result = response.body().getAttachment();
                                SPUtils.getInstance(mContext).putFloatValue(SPKey.GASOLINE_LIMIT, result.getBackOilCarDistanceLimit());
                                SPUtils.getInstance(mContext).putFloatValue(SPKey.GASOLINE_MILEAGE, result.getOilMileageThreshold());
                                overlayUtils.getCityList();
                            } else if (response.body().getStatus() == 20) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<InitBean> call, Throwable t) {
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.d("netError", "001");
                    }
                });
    }

    //弹框海报
    private void getNewPost() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getNewPost(MyApplication.getInstance().getRequestFieldMap(), MyApplication.getInstance().getRequestFieldMap().get("areaCode")).enqueue(new Callback<PostNewBean>() {
            @Override
            public void onResponse(Call<PostNewBean> call, final Response<PostNewBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getMsg_code() == 200) {
                        if (response.body().getData().size() > 0) {
                            ArrayList<String> imageList = new ArrayList<>();
                            ArrayList<String> urlList = new ArrayList<>();
                            ArrayList<String> titleList = new ArrayList<>();
                            for (int i = 0; i < response.body().getData().size(); i++) {
                                imageList.add(response.body().getData().get(i).getCover());
                                urlList.add(response.body().getData().get(i).getLink());
                                titleList.add(response.body().getData().get(i).getName());
                            }
                            Glide.with(MyApplication.getInstance()).load(response.body().getData().get(0).getCover()).asBitmap().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                                    PostDialog postDialog = new PostDialog(mContext, imageList, urlList, titleList);
                                    dialogQueue.showDialog(postDialog);
                                }

                                @Override
                                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                }
                            });
                        }
                    } else if (response.body().getMsg_code() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    }
                }
            }

            @Override
            public void onFailure(Call<PostNewBean> call, Throwable t) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    //寻车弹框海报
    private void getPopPost(final String entry) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getPopPost(MyApplication.getInstance().getRequestFieldMap(), entry).enqueue(new Callback<PopPostBean>() {
            @Override
            public void onResponse(Call<PopPostBean> call, final Response<PopPostBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().size() != 0) {
                            ArrayList<String> imageList = new ArrayList<>();
                            ArrayList<String> urlList = new ArrayList<>();
                            ArrayList<String> titleList = new ArrayList<>();
                            for (int i = 0; i < response.body().getAttachment().size(); i++) {
                                imageList.add(response.body().getAttachment().get(i).getImgUrl());
                                urlList.add(response.body().getAttachment().get(i).getH5Url());
                                String title = "活动中心";
                                titleList.add(title);
                            }
                            if ("1".equals(entry)) {//进入app时可弹出
                                Glide.with(MyApplication.getInstance()).load(response.body().getAttachment().get(0).getImgUrl()).asBitmap().into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                                        PostDialog postDialog = new PostDialog(mContext, imageList, urlList, titleList);
                                        dialogQueue.showDialog(postDialog);
                                    }

                                    @Override
                                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                    }
                                });
                            } else if ("2".equals(entry)) {//进入寻车可弹出
                                final Intent intent = new Intent(mContext, PopPostFindCarActivity.class);
                                intent.putStringArrayListExtra("imageList", imageList);
                                intent.putStringArrayListExtra("urlList", urlList);
                                intent.putStringArrayListExtra("titleList", titleList);
                                ThreadPool.execute(() -> {
                                    try {
                                        Glide.with(mContext)
                                                .load(response.body().getAttachment().get(0).getImgUrl())
                                                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                                                .listener(new RequestListener<String, GlideDrawable>() {
                                                    @Override
                                                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                                        return false;
                                                    }

                                                    @Override
                                                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                                        startActivity(intent);
                                                        return false;
                                                    }
                                                })
                                                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                                .get();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        }
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    }
                }
            }

            @Override
            public void onFailure(Call<PopPostBean> call, Throwable t) {
                //ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 检查是否有进行中的行程
     */
    private void hasExistingTravel() {

        getUnOrder(new OrderRepository.GetUnfinishedOrderDone() {
            @Override
            public void onHaveOrder(@NotNull UnFinishedOrderBean data) {
                RxBus.getInstance().post(new GetUnFinishedEvent(1, OrderRepository.orderId, OrderRepository.rentType));
            }

            @Override
            public void onNoOrder() {
                Logger.d("jsonPhraseResult", "通知无订单");
                RxBus.getInstance().post(new GetUnFinishedEvent(0, null, 0));
            }

            @Override
            public void onError(@NotNull String message) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                isLoadingDone = true;
                Logger.d("netError", "查询进行中订单失败  " + message);
            }
        });

    }

    /**
     * 检查是否有进行中的行程,之后不加载地图图标
     */
    private void hasExistingTravelNotLoadMarker() {
        getUnOrder(new OrderRepository.GetUnfinishedOrderDone() {
            @Override
            public void onHaveOrder(@NotNull UnFinishedOrderBean data) {
            }

            @Override
            public void onNoOrder() {

            }

            @Override
            public void onError(@NotNull String message) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                isLoadingDone = true;
                Logger.d("netError", "查询进行中订单失败  " + message);
            }
        });
    }


    //选车获取附近车辆和网点,共20辆车,弹出网点详情布局
    public void getNearTwenty(boolean hasCityMarker) {
        //showLoadingDialog();
        StateType.setCurState(PAGER_NEAR);
        overlayUtils.getNearTwenty(curPosition, (errorCode, nearCarList) -> {
            if (errorCode == LOAD_SUCCESS) {
                overlayUtils.clearMap();
                overlayUtils.markerOverlay.addNearTwentyMarker(nearCarList);
                dismissLoadingDialog();
                layout_find_car.setVisibility(View.GONE);
                findCarFee.setVisibility(View.GONE);
                tabSwitchView.setDefault();

                carsPagerAdapter = new CarsPagerAdapter(mContext, nearCarList, overlayUtils.markerOverlay.picMap);
                if (nearCarList.size() == 1) {
                    vpCar.canLoop(false);
                } else {
                    vpCar.canLoop(true);
                }
                vpCar.setPageMargin((int) TypedValue.applyDimension(COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
                //vpCar.setOffscreenPageLimit(2);
                vpCar.setAdapter(carsPagerAdapter);
                // selectedItemPosition = 1;
                //vpCar.setCurrentItem(selectedItemPosition, false);
                LatLng carPosition = null;
                //附近20 车
                carPosition = new LatLng((carsPagerAdapter.getItem(0)).getLatitude(), (carsPagerAdapter.getItem(0)).getLongitude());
                controlLayout(layout_car_pager, true, carPosition);
                if (hasCityMarker) {
                    mapStatusUtils.animateMove(carPosition, 17, 600);
                }
                overlayUtils.addBounds();
            } else {
                StateType.setCurState(DEFAULT);
                final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                dialogOneButton.setCancelable(true);
                dialogOneButton.setCanceledOnTouchOutside(true);
                dialogOneButton.setTitle("抱歉");
                dialogOneButton.setMessage("附近暂无可用车辆");
                dialogOneButton.setYesOnclickListener("知道了", () -> dialogOneButton.dismiss());
                dialogQueue.showDialog(dialogOneButton);
            }
        });
    }


    private void noService() {
        ToastUtils.makeText(mContext, "尚未开通该城市", 1, ToastUtils.LENGTH_SHORT).show();
    }


    public void getInitData() {
        //获取城市信息
        getCityInfo();
        //获取基础配置信息
        initAppData();
        GetAppConfig.getInstance(mContext).getAppConstants();
    }

    //获取城市信息
    public void getCityInfo() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getCityInfo(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CityDetailBean>() {
                    @Override
                    public void onResponse(Call<CityDetailBean> call, Response<CityDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200 && response.body().getAttachment() != null) {
                                if (response.body().getAttachment().getIsClear() == 1) {
                                    SPUtils.getInstance(mContext).removeValue(response.body().getAttachment().getClearCacheKey());
                                }
                                SPUtils.getInstance(mContext).putStringValue(SPKey.CACHE_KEY, response.body().getAttachment().getCacheKey());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.CLEAR_KEY, response.body().getAttachment().getClearCacheKey());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.DOT_ISEXITE, response.body().getAttachment().getIsExist());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.WALLET_PICTURE, response.body().getAttachment().getRushedSendPicture());
                                if (response.body().getAttachment().getIsExist() == 1 && SPUtils.getInstance(mContext).getIntValue(response.body().getAttachment().getCacheKey()) == 0) {
                                    imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center_dot));
                                    iv_wallet_reddot.setVisibility(View.VISIBLE);
                                }
                                SPUtils.getInstance(mContext).putIntValue(SPKey.DEPOSIT_CAR, response.body().getAttachment().getEnclosure().getCarBail());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_ALIPAY_OPEN, response.body().getAttachment().getEnclosure().getAliPay());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_WXPAY_OPEN, response.body().getAttachment().getEnclosure().getWechatPay());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_SHARE_INVITE, response.body().getAttachment().getEnclosure().getActUserShare());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.FIND_CAR_DISTANCE, response.body().getAttachment().getEnclosure().getFindCarDistance());
                                SPUtils.getInstance(mContext).putIntValue(SPKey.IS_CITY_OPEN, response.body().getAttachment().getEnclosure().getIsCar());
                                if (response.body().getAttachment().getEnclosure().getIsCar() != 1) {
                                    noService();
                                } else {
                                }
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }

                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CityDetailBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Logger.d("netError", t.getMessage());
                    }
                });

    }

    //寻电车中订单
    private void updateFindCarInfo() {
        //获取订单详情
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getTravelDetail(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TravelDetailBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(TravelDetailBean travelDetailBean) {
                        if (travelDetailBean.getStatus() == 200 && travelDetailBean.getAttachment() != null) {
                            OrderRepository.carId = travelDetailBean.getAttachment().getCarId();
                            updateCarDetail(travelDetailBean.getAttachment());
                        } else {
                            ToastUtils.makeText(mContext, travelDetailBean.getMessage(), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    private void updateCarDetail(TravelDetailBean.AttachmentBean orderModel) {
        //更新车的信息
        Observable<CarInfoBean> carInfoObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getCarInfo(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<CarInfoBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象，以便后续兼容错误处理
                            emitter.onNext(new CarInfoBean());
                            emitter.onComplete();
                        }));

        //获取金豆车信息
        Observable<GoldCarOneBean> goldOneCarObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getGoldOneCar(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<GoldCarOneBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象
                            emitter.onNext(new GoldCarOneBean());
                            emitter.onComplete();
                        }));
        //还车备注信息
        Observable<ReturnCarCommentBean> returnCarCommentObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getReturnCarComment("epimetheus/v1/rcc/" + OrderRepository.carId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<ReturnCarCommentBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象，以便后续兼容错误处理
                            emitter.onNext(new ReturnCarCommentBean());
                            emitter.onComplete();
                        }));

        Observable.zip(carInfoObservable, goldOneCarObservable, returnCarCommentObservable, (carInfoBean, goldCarOneBean, returnCarCommentBean) -> {

            ContentBean carBean = new ContentBean();//这个Bean聚合三个接口的数据，方便数据后续的处理和使用
            if (carInfoBean != null && carInfoBean.getStatus() == 200 && carInfoBean.getAttachment() != null) {
                carBean.setLatitude(carInfoBean.getAttachment().getLatitude());
                carBean.setLongitude(carInfoBean.getAttachment().getLongitude());
                carBean.setMapPic(carInfoBean.getAttachment().getMapPic());
            }
            if (goldCarOneBean != null && goldCarOneBean.getMsg_code() == 200 && goldCarOneBean.getAttachment() != null) {
                carBean.setGoldCarStatus(goldCarOneBean.getAttachment().getCar_status());
                carBean.setGoldCarType(goldCarOneBean.getAttachment().getGold_car_type());
                carBean.setGoldCarMinutes(goldCarOneBean.getAttachment().getShort_minutes());
            }

            if (returnCarCommentBean != null && returnCarCommentBean.getMsg_code() == 200 && returnCarCommentBean.getAttachment() != null) {
                carBean.setImgs(returnCarCommentBean.getAttachment().getComment().getImgs());
                carBean.setOnGround(returnCarCommentBean.getAttachment().getComment().getOnGround());
                carBean.setRemarkMsg(returnCarCommentBean.getAttachment().getComment().getRemarkMsg());
            }
            return carBean;
        })
                .onErrorResumeNext((Function<Throwable, ObservableSource<ContentBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象，以便后续兼容错误处理
                            emitter.onNext(new ContentBean());
                            emitter.onComplete();
                        }))
                .subscribe(new Observer<ContentBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoadingDialog();
                    }

                    @Override
                    public void onNext(ContentBean carBean) {
                        dismissLoadingDialog();
                        Logger.i("goldBean", "zoudoalezheli1");
                        //展示选中的车详情
                        loadFindCarLayout(orderModel, carBean);
                        //更新这个车的Marker信息
                        overlayUtils.updateOneMarkerInfo(carBean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void loadFindCarLayout(TravelDetailBean.AttachmentBean orderModel, ContentBean carBean) {
        //取数据
        OrderRepository.carId = orderModel.getCarId();
        OrderRepository.orderId = orderModel.getId();
        OrderRepository.rentType = orderModel.getRentType();
        OrderRepository.bookType = orderModel.getBookType();
        OrderRepository.cancelCount = orderModel.getLeftCancelTimes();
        String picId = orderModel.getCarModel().getPicture();
        String license = orderModel.getCarModel().getLicenseTag();
        String brandModel = orderModel.getCarModel().getBrand() + " " + orderModel.getCarModel().getModelCN();

        OrderRepository.overPlusTime = orderModel.getOverplusTime() * 1000 + 2000;
        OrderRepository.totalTime = orderModel.getCarFindTime() * 1000;
        Logger.i("totalTimeCur", OrderRepository.totalTime + "");
        if (carBean.getLatitude() == 0 || carBean.getLongitude() == 0) {
            carBean.setLatitude(orderModel.getCarModel().getLatitude());
            carBean.setLongitude(orderModel.getCarModel().getLongitude());
        }
        //使用数据
        tx_place_order_plate.setText(license);
        find_car_brandModel.setText(brandModel);
        layout_car_pager.setVisibility(View.GONE);
        if (SPUtils.getInstance(mContext).getIntValue(SPKey.PARKFEE_CLICK) == 0) { //没点击过
            findCarFee.setBackground(getResources().getDrawable(R.drawable.park_fee_tips_blue));
        } else {
            findCarFee.setBackground(getResources().getDrawable(R.drawable.park_fee_tips_white));
        }
        foundCarPosition = new LatLng(carBean.getLatitude(), carBean.getLongitude());

        if (OrderRepository.bookType == 4) {
            contact_deliver.setVisibility(View.VISIBLE);
        } else {
            contact_deliver.setVisibility(View.GONE);
        }
        find_car_current.setVisibility(View.GONE);
        controlLayout(layout_find_car, true, new LatLng(foundCarPosition.latitude, foundCarPosition.longitude));
        if (StateType.getCurState() == StateType.State.SHOW_PAGER) {
            overlayUtils.removeNearTwentyMarker();
            overlayUtils.addFindCar(foundCarPosition, carBean.getMapPic());
        } else {
            overlayUtils.clearMap();
            overlayUtils.addFindCar(foundCarPosition, carBean.getMapPic());
            overlayUtils.addBounds();
        }
        StateType.setCurState(StateType.State.CAR_FIND);


        Logger.i("goldBean", "是否金豆车d" + carBean.getGoldCarStatus());
        overlayUtils.showFindCarInfoWindow(carBean, 0);

        ImageLoader.getInstance().displayImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + picId, iv_order_car);
        findCarTimer();

        RoutePlan.getInstance().clearRoutePlanning();
        RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition, foundCarPosition, null);
        overlayUtils.getReturnCarTrack(OrderRepository.carId);//查询还车轨迹
        getPopPost("2");//寻车时的提醒海报

        //如果人车位置小于特定距离，显示车辆操作按钮，否则不显示
        if (DistanceUtil.getDistance(curPosition, foundCarPosition) <= SPUtils.getInstance(mContext).getIntValue(SPKey.FIND_CAR_DISTANCE)) {
            find_car_open.setVisibility(View.VISIBLE);
            find_car_find.setVisibility(View.VISIBLE);
            find_car_qipao.setVisibility(View.GONE);
        } else {
            find_car_open.setVisibility(View.GONE);
            find_car_find.setVisibility(View.GONE);
            find_car_qipao.setVisibility(View.VISIBLE);
        }
        RxBus.getInstance().toObservable(H5CancelOrderEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(h5CancelOrderEvent -> {
            Logger.d("sgagdag", "取消订单了");
            if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                if (BluetoothHelper.getInstance().isConnect()) {
                    BluetoothHelper.getInstance().disConnectDevice();
                } else {
                    BluetoothHelper.getInstance().stopScanDevice();
                }
            }

            //ToastUtils.makeText(mContext, getResources().getString(R.string.cancelOrderSuccess), 0, ToastUtils.LENGTH_SHORT).show();
            if (timer != null) {
                timer.cancel();
                timer = null;
            }

            StateType.setCurState(StateType.State.DEFAULT);
            resetStatus(false, false);
            // controlLayout(layout_find_car, false, null);
            overlayUtils.clearMap();
            getParksAndCarsByPages(true, true);

        });

    }

    //寻车倒计时
    private void findCarTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        Logger.i("totalTimeCurplaceOrderTimer", OrderRepository.totalTime + "");
        timer = new CountDownTimer(OrderRepository.overPlusTime, 1000) {
            @Override
            public void onTick(long l) {//15min
                OrderRepository.overPlusTime = l;
                tx_reserve_order_timer.setText(TimeUtils.formatSecondCountNoZero(l / 1000 + ""));

                countDownIndicate.setProgress((int) ((double) l / (OrderRepository.totalTime == 0 ? 15 * 60 * 1000 : OrderRepository.totalTime) * 100));
                Logger.d("30s", l % 30000 + "");

                if (l % 30000 < 1000 && l != 60 * 15 * 1000 && l > 1000) {//每30秒上传一次日志
                    Logger.d("30s", "背后弹出");
                    ThreadPool.execute(() -> {
                        try {
                            ApiStore.getInstance().getLogApiService(UrlContainer.Request.BASE_GATE_URL).commitFindCarLog(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId).execute();
                        } catch (IOException e) {
                            //e.printStackTrace();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                if (OrderRepository.bookType == 4) {//送车上门，倒计时结束自动跳行驶中
                    notifyOrderStatusChange();
                } else {//其他类型，自动取消订单。
                    autoCancelOrder();
                }
            }
        };
        timer.start();
    }


    //服务器获取是否跳转取消订单原因页面
    private void autoCancelOrder() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkAutoCancel(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId).enqueue(new Callback<CheckCarOrderBean>() {
            @Override
            public void onResponse(Call<CheckCarOrderBean> call, final Response<CheckCarOrderBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200 || response.body().getStatus() == 400) {
                        if (timer != null) {
                            timer.cancel();
                        }
                        timer = null;
                        compositeDisposable.clear();//取消获取行车轨迹的订阅
                        overlayUtils.clearMap();
                        StateType.setCurState(StateType.State.DEFAULT);
                        controlLayout(layout_find_car, false, null);
                        //停止蓝牙搜索，或者断开连接
                        if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                            if (BluetoothHelper.getInstance().isConnect()) {
                                BluetoothHelper.getInstance().disConnectDevice();
                            } else {
                                BluetoothHelper.getInstance().stopScanDevice();
                            }
                        }

                        getParksAndCarsByPages(true, true);

                        final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                        dialogOneButton.setTitle("提醒");
                        dialogOneButton.setMessage("订单超时已取消");
                        dialogOneButton.setYesOnclickListener("好的", () -> {
                            if (response.body().getAttachment() != null && "1".equals(response.body().getAttachment().getIsPrompt())) {
                                Intent intent = new Intent();
                                intent.setClass(mContext, WebViewActivity.class);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "取消原因");
                                CookieManager cookieManager = CookieManager.getInstance();
                                cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_order_feedback), "orderId=" + OrderRepository.orderId);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_order_feedback));
                                startActivity(intent);
                            }
                            dialogOneButton.dismiss();
                        });
                        dialogQueue.showDialog(dialogOneButton);
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<CheckCarOrderBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    private void notifyOrderStatusChange() {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("orderId", OrderRepository.orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).notifyOrderStatusChange(body)
                .retry(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResultBean resultBean) {
                        dismissLoadingDialog();
                        if (resultBean.getStatus().equals("200")) {
                            find_car_begin.setVisibility(View.VISIBLE);

                            find_car_current.setVisibility(View.VISIBLE);
                           /* final Intent intent = new Intent(mContext, DrivingActivity.class);
                            intent.putExtra(IntentKey.INTENT_ORDER_ID, OrderRepository.orderId);
                            intent.putExtra(IntentKey.INTENT_STEP, "findCar");
                            startActivity(intent);*/

                        } else {
                            ToastUtils.makeText(mContext, resultBean.getMessage(), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 仅网络开车门，不带提示开蓝牙
     */
    public void rxOpenCarDoorOnlyNet() {
        showLoadingDialog();
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).openCar(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId, OrderRepository.carId, "0", "0")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OperateBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(OperateBean operateBean) {
                        dismissLoadingDialog();
                        Logger.i("main net openDoor", operateBean.getMessage() + "");
                        if (operateBean.getStatus() == 200) {
                            Logger.d("bleinfo", "主页网络开车门成功");
                            //BluetoothHelper.getInstance().stopScanDevice();

                            //停止寻车计时器
                            if (timer != null) {
                                timer.cancel();
                                timer = null;
                            }

                            //下单寻车布局消失
                            findCarFee.setVisibility(View.GONE);
                            StateType.setCurState(StateType.State.DEFAULT);
                            controlLayout(layout_find_car, false, null);
                            contact_deliver.setVisibility(View.GONE);
                            final Intent intent = new Intent(mContext, DrivingActivity.class);
                            intent.putExtra(IntentKey.INTENT_ORDER_ID, OrderRepository.orderId);
                            intent.putExtra(IntentKey.INTENT_STEP, "findCar");
                            startActivity(intent);
                            if (couponCountdown != null)
                                couponCountdown.setVisible(View.GONE);
                            RxBus.getInstance().post(new CountDownCloseEvent(true));
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    StateType.setCurState(StateType.State.DEFAULT);
                                    controlLayout(layout_find_car, false, null);
                                    overlayUtils.clearMap();
                                    getParksAndCarsByPages(true, true);
                                }
                            }, 1000);
                        } else if (operateBean.getStatus() == 20) {
                            ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            startActivity(intent);
                            AppManager.getAppManager().finishActivity();
                        } else if (operateBean.getStatus() == 404) {
                            ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                        } else {
                            ToastUtils.makeText(mContext, operateBean.getMessage(), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        Logger.i("main net openDoor", "onFailure" + e.getMessage());
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    //寻车
    public void findCar() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).findCar(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId, OrderRepository.carId).enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        ToastUtils.makeText(mContext, "鸣笛成功", 0, ToastUtils.LENGTH_SHORT).show();
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    } else if (response.body().getStatus() == 404) {
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    //取消电车订单
    public void cancelCarOrder() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).cancelOrder(MyApplication.getInstance().getRequestFieldMap(), OrderRepository.orderId).enqueue(new Callback<CancelOrder>() {
            @Override
            public void onResponse(Call<CancelOrder> call, Response<CancelOrder> response) {
                if (response.isSuccessful() && response.body() != null) {
                    dismissLoadingDialog();
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getOrders().getStatus() == 102) {

                            if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                                if (BluetoothHelper.getInstance().isConnect()) {
                                    BluetoothHelper.getInstance().disConnectDevice();
                                } else {
                                    BluetoothHelper.getInstance().stopScanDevice();
                                }
                            }

                            //ToastUtils.makeText(mContext, getResources().getString(R.string.cancelOrderSuccess), 0, ToastUtils.LENGTH_SHORT).show();
                            if (timer != null) {
                                timer.cancel();
                            }
                            timer = null;

                            compositeDisposable.clear();//取消获取行车轨迹的订阅


                            if (response.body().getAttachment() != null && "1".equals(response.body().getAttachment().getIsPrompt())) {
                                Intent intent = new Intent();
                                intent.setClass(mContext, WebViewActivity.class);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "取消原因");
                                CookieManager cookieManager = CookieManager.getInstance();
                                cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_order_feedback), "orderId=" + OrderRepository.orderId);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_order_feedback));
                                startActivity(intent);
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        StateType.setCurState(StateType.State.DEFAULT);
                                        controlLayout(layout_find_car, false, null);
                                        overlayUtils.clearMap();
                                        contact_deliver.setVisibility(View.GONE);
                                        getParksAndCarsByPages(true, true);
                                    }
                                }, 1000);
                            } else {
                                StateType.setCurState(StateType.State.DEFAULT);
                                controlLayout(layout_find_car, false, null);
                                overlayUtils.clearMap();
                                getParksAndCarsByPages(true, true);
                            }


                        }
                        mapStatusUtils.animateMove(curPosition, 17, 600, 0);

                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CancelOrder> call, Throwable t) {
                dismissLoadingDialog();
                Logger.d("okhttp", t.getMessage() + "");
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 控制布局和按钮的弹出或者隐退
     *
     * @param view   要弹出或隐藏的布局
     * @param isShow 电车的布局 弹出或隐藏
     */
    private void controlLayout(View view, boolean isShow, LatLng carPosition) {
        try {
            view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            float layoutHeight = DensityUtils.px2dp(mContext, view.getMeasuredHeight());
            if (view == layout_car_pager) {
                if (isShow) {
                    if (TextUtils.isEmpty(SPUtils.getInstance(mContext).getStringValue(SPKey.ABATEMENT_CHECK)) ||
                            SPUtils.getInstance(mContext).getStringValue(SPKey.ABATEMENT_CHECK).equals("0")) {
                        abatementCheckBox.setChecked(false);
                    } else {
                        abatementCheckBox.setChecked(true);
                    }

                    useCar.setVisibility(View.GONE);
                    mapStatusUtils.animateMove(carPosition, 0, 500, (int) layoutHeight - 120);
                    setAnimator(view, layoutHeight, 0f, true);
                    setAnimator(imageViewLocate, 0f, -(layoutHeight - 93), true);//start：此值越小，距离越大
                    setAnimator(imageViewCenter, 0f, -(layoutHeight - 93), true);
                } else {
                    // mapStatusUtils.animateMove(curPosition, 19, 300, 0);
                    setAnimator(imageViewLocate, -(layoutHeight - 93), 0f, false);
                    setAnimator(imageViewCenter, -(layoutHeight - 93), 0f, false);
                    setAnimator(view, 0f, layoutHeight, false);
                }
            } else if (view == layout_find_car) {
                if (isShow) {
                    useCar.setVisibility(View.GONE);
                    mapStatusUtils.animateMove(carPosition, 17, 500, (int) layoutHeight - 120);
                    setAnimator(view, layoutHeight, 0f, true);
                    setAnimator(imageViewLocate, 0f, -(layoutHeight - 30), true);
                    setAnimator(imageViewCenter, 0f, -(layoutHeight - 30), true);
                } else {
                    mapStatusUtils.animateMove(curPosition, 0, 300, 0);
                    findCarFee.setVisibility(View.GONE);
                    setAnimator(imageViewLocate, -(layoutHeight - 30), 0f, false);
                    setAnimator(imageViewCenter, -(layoutHeight - 30), 0f, false);
                    setAnimator(view, 0f, layoutHeight, false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //下单(预约车)，然后开始寻车15分钟倒计时
    public void rentCar(String isAbatement, ConfirmDayRentDialog confirmChooseDaysDialog) {
        showLoadingDialog();
        String rentType = "1";
        if (tabSwitchView.getSelected() == 1) {
            rentType = "5";
        } else if (tabSwitchView.getSelected() == 2) {
            rentType = "2";
        }
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).rentCar(MyApplication.getInstance().getRequestFieldMap(),
                OrderRepository.carId, isAbatement,
                tabSwitchView.getSelected() == 1 || tabSwitchView.getSelected() == 2 ? "1" : null, rentType, tabSwitchView.getEndTime(),
                tabSwitchView.getLittleDaySelectedId())
                .enqueue(new Callback<PlaceOrderBean>() {
                    @Override
                    public void onResponse(Call<PlaceOrderBean> call, final Response<PlaceOrderBean> response) {

                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                //预约成功后的处理
                                //清除还车cache
                                if (confirmChooseDaysDialog != null) {
                                    confirmChooseDaysDialog.dismiss();
                                }
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_SPINNER_NAME);
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PARKNAME);
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PARKNUM);
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_POSITION);
                                SPUtils.getInstance(mContext).putIntValue(SPKey.PARKFEE_CLICK, 0);
                                OrderRepository.orderId = response.body().getAttachment().getOrder().getId();
                                updateFindCarInfo();
                            } else if (response.body().getStatus() == 20) {
                                if (confirmChooseDaysDialog != null) {
                                    confirmChooseDaysDialog.dismiss();
                                }
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            } else if (response.body().getStatus() == 401) {
                                if (confirmChooseDaysDialog != null) {
                                    confirmChooseDaysDialog.dismiss();
                                }
                                checkUserCertifyStatus();
                            } else if (response.body().getStatus() == 402 || response.body().getStatus() == 403) {
                                if (confirmChooseDaysDialog != null) {
                                    confirmChooseDaysDialog.dismiss();
                                }
                                checkUserCertifyStatus();
                            } else if (response.body().getStatus() == 404) {
                                getUnOrder(new OrderRepository.GetUnfinishedOrderDone() {
                                    @Override
                                    public void onHaveOrder(@NotNull UnFinishedOrderBean data) {
                                        dismissLoadingDialog();
                                    }

                                    @Override
                                    public void onNoOrder() {
                                        dismissLoadingDialog();
                                    }

                                    @Override
                                    public void onError(@NotNull String message) {
                                        dismissLoadingDialog();
                                    }
                                });

                            } else if (response.body().getStatus() == 405) {
                                dismissLoadingDialog();
                                final DialogTwoButton inCarDialog = new DialogTwoButton(MainActivity.this);
                                inCarDialog.setTitle("提示");
                                inCarDialog.setMessage(response.body().getMessage());
                                inCarDialog.setYesOnclickListener("去往我的钱包", new DialogTwoButton.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        inCarDialog.dismiss();
                                        if (confirmChooseDaysDialog != null) {
                                            confirmChooseDaysDialog.dismiss();
                                        }
                                        Intent intent_wallet = new Intent(mContext, WebViewActivity.class);
                                        intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的钱包");
                                        CookieManager cookieManager2 = CookieManager.getInstance();
                                        cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "isExist=" + SPUtils.getInstance(mContext).getIntValue(SPKey.DOT_ISEXITE));
                                        cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "RushedSendPicture=" + SPUtils.getInstance(mContext).getStringValue(SPKey.WALLET_PICTURE));
                                        intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet));
                                        startActivity(intent_wallet);
                                    }
                                });
                                inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setCancelable(false);
                                dialogQueue.showDialog(inCarDialog);
                            } else if (response.body().getStatus() == 409) {
                                dismissLoadingDialog();
                                final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                                inCarDialog.setTitle("提示");
                                inCarDialog.setMessage(response.body().getMessage());
                                inCarDialog.setYesOnclickListener("去认证", () -> {
                                    if (confirmChooseDaysDialog != null) {
                                        confirmChooseDaysDialog.dismiss();
                                    }
                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_margin_certification));
                                    startActivity(intent);
                                    inCarDialog.dismiss();
                                });
                                inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
                                dialogQueue.showDialog(inCarDialog);
                            } else if (response.body().getStatus() == 410) {
                                dismissLoadingDialog();
                                final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                                inCarDialog.setTitle("提示");
                                inCarDialog.setMessage(response.body().getMessage());
                                inCarDialog.setYesOnclickListener("去认证", () -> {
                                    if (confirmChooseDaysDialog != null) {
                                        confirmChooseDaysDialog.dismiss();
                                    }
                                    getZhiMaShouQuanUrl();
                                    inCarDialog.dismiss();
                                });
                                inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
                                dialogQueue.showDialog(inCarDialog);
                            } else if (response.body().getStatus() == 413) {
                                dismissLoadingDialog();
                                final DialogTwoButton inCarDialog = new DialogTwoButton(MainActivity.this);
                                inCarDialog.setTitle("您有未处理的违章");
                                inCarDialog.setMessage("请您处理后再用车");
                                inCarDialog.setYesOnclickListener("查看详情", new DialogTwoButton.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        if (confirmChooseDaysDialog != null) {
                                            confirmChooseDaysDialog.dismiss();
                                        }
                                        Intent intent_weizhang = new Intent(mContext, WebViewActivity.class);
                                        intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "违章查询");
                                        intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_break_rules));
                                        startActivity(intent_weizhang);
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setNoOnclickListener("好的", new DialogTwoButton.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setCancelable(false);
                                dialogQueue.showDialog(inCarDialog);
                            } else if (response.body().getStatus() == 414) {
                                dismissLoadingDialog();
                                final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                                inCarDialog.setTitle("信用等级不足");
                                inCarDialog.setMessage("是否升级信用等级？");
                                inCarDialog.setYesOnclickListener("了解一下", () -> {
                                    if (confirmChooseDaysDialog != null) {
                                        confirmChooseDaysDialog.dismiss();
                                    }
                                    Intent intent = new Intent();
                                    intent.setClass(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_success_identity));
                                    startActivity(intent);
                                    inCarDialog.dismiss();
                                });
                                inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
                                dialogQueue.showDialog(inCarDialog);
                            } else if (response.body().getStatus() == 418) {
                                dismissLoadingDialog();
                                startActivity(new Intent(mContext, CertifyDrivelicenseActivity.class));
                            } else {
                                dismissLoadingDialog();
                                final DialogOneButton inCarDialog = new DialogOneButton(mContext);
                                inCarDialog.setTitle("订车失败");
                                inCarDialog.setMessage(response.body().getMessage());
                                inCarDialog.setYesOnclickListener("知道了", () -> {
                                    if (confirmChooseDaysDialog != null) {
                                        confirmChooseDaysDialog.dismiss();
                                    }
                                    onBackPressed();
                                    inCarDialog.dismiss();
                                });
                                dialogQueue.showDialog(inCarDialog);
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<PlaceOrderBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Logger.d("netError20", t.toString());
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //验证用户汽车认证状态
    private void checkUserCertifyStatus() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getUserStatus(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_AMOUNT, response.body().getAttachment().getCarBail() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.JISHEN_STATUS, response.body().getAttachment().getStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_STATUS, response.body().getAttachment().getAuthorize() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_FEN, response.body().getAttachment().getScore() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.XINYONG_LEVEL, response.body().getAttachment().getLevel() + "");


                        int deposit = response.body().getAttachment().getDepositStatus();
                        int authorize = response.body().getAttachment().getAuthorize();
                        int jishenStatus = response.body().getAttachment().getStatus();
                        int licenseStatus = response.body().getAttachment().getLicenseStatus();
                        if (authorize != 1 && deposit == 0) {
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_credit_auth));
                            startActivity(intent);
                        } else if ("11".equals(licenseStatus)) {
                            final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                            dialogOneButton.setTitle("提示");
                            dialogOneButton.setMessage("身份信息审核中，请耐心等待");
                            dialogOneButton.setCancelable(false);
                            dialogOneButton.setCanceledOnTouchOutside(false);
                            dialogOneButton.setYesOnclickListener("确定", new DialogOneButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    dialogOneButton.dismiss();
                                }
                            });
                            dialogQueue.showDialog(dialogOneButton);
                        } else {
                            //未实名
                            Intent intent = new Intent(mContext, CertifyCardActivity.class);
                            startActivity(intent);
                        }
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onResume() {
        useCar.setVisibility(View.VISIBLE);
        mapView.onResume();
        if (isExecuteOnResumeCheckOrder)
            if (!StateType.isEqualsCurStates(StateType.State.CAR_FIND) && !isFirstLocation
                    && null != SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID)) { //如果当前显示的就是寻车中，不查询订单
                hasExistingTravelNotLoadMarker();
            }
        isExecuteOnResumeCheckOrder = true;
        if (!isFirstLocation) {
            startLocation();
            //刷新地图图标
            if (curPosition != null && isLoadingDone
                    && StateType.isEqualsCurStates(StateType.State.DEFAULT) && !overlayUtils.markerOverlay.hasCityMarker) {
                if ((new Date().getTime() - SPUtils.getInstance(mContext).getLongValue(SPKey.REFRESH_TIME)) > 240000 || overlayUtils.markerOverlay.carMarkerOptionsMap.size() == 0) {
                    getParksAndCarsByPages(true, true);
                }
            }
        }

        if (StateType.isEqualsCurStates(StateType.State.CAR_FIND) && OrderRepository.overPlusTime > 1000) {
            checkOrderStatus(true);
        }
/*        if (!StateType.isEqualsCurStates(StateType.State.CAR_FIND)) {
            if (SPUtils.getInstance(mContext).getIntValue(SPKey.IS_CITY_OPEN) == 1) {
                layoutSendService.setVisibility(View.VISIBLE);
            }
        }*/

        if (couponCountdown != null && couponCountdown.getVisibility() == View.VISIBLE && couponCountdown.getStatus() == 1) {
            getCouponCountDown(getFirstCarEventCreated);
        }


        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);

        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }


    /**
     * 分页加载车和网点
     */
    private void getParksAndCarsByPages(boolean isShowLoading, boolean clearMap) {
        Logger.d("goldBean", "开始分页加载");
        if (StateType.loadState == StateType.LoadMarkerState.LOADING) {
            return;
        }
        useCar.setVisibility(View.VISIBLE);
        //如果距上次网络刷新大于4分钟，或者之前没有加载过车，则网络请求刷新车和网点
        if ((new Date().getTime() - SPUtils.getInstance(mContext).getLongValue(SPKey.REFRESH_TIME)) > 240000 || overlayUtils.markerOverlay.carMarkerOptionsMap.size() == 0) {
            if (isShowLoading) {
                showLoadingDialog();
            }
            StateType.loadState = StateType.LoadMarkerState.LOADING;
            SPUtils.getInstance(mContext).putLongValue(SPKey.REFRESH_NEAR_TIME, 0);//所有车刷新后，二十辆的刷新时间置零
            overlayUtils.getCarsByPage(curPosition, new OverlayUtils.OnLoadCarResult() {
                @Override
                public void onFirstPageLoadDone(int errorCode, String error) {
                    //车的第一页加载完
                    dismissLoadingDialog();
                    if (errorCode == LOAD_SUCCESS) {
                        SPUtils.getInstance(mContext).putLongValue(SPKey.REFRESH_TIME, new Date().getTime());
                    } else if (errorCode == LOAD_ERROR) {
                        dismissLoadingDialog();
                    }

                    if (errorCode != LOAD_LOGOUT) {
                        overlayUtils.addBounds();
                    }
                    Logger.d("jsonPhraseResult", "通知第一页完毕1");

                    ContentBean carBean = overlayUtils.getNearOneCar(curPosition);
                    if (carBean != null) {
                        RxBus.getInstance().post(new GetFirstCarEvent(carBean.getId(), carBean.getLatitude(), carBean.getLongitude()));
                    } else {
                        RxBus.getInstance().post(new GetFirstCarEvent(null, 0, 0));
                    }
                }

                @Override
                public void onCarsLoadDone(int errorCode, String error) {
                    //所有车加载完
                    StateType.loadState = StateType.LoadMarkerState.LOAD_DONE;

                }
            });
        } else if (StateType.loadState != StateType.LoadMarkerState.LOADING) {
            //加载已有的marker数据到地图(不从网络重新请求)，如果网络刷新还没加载完，不执行下面的代码
            StateType.loadState = StateType.LoadMarkerState.LOADING;
            overlayUtils.markerOverlay.hideInfoWindow();
            if (clearMap) {
                overlayUtils.clearMap();
                overlayUtils.addAllPagesCarsMarker();
                overlayUtils.addBounds();
            } else {
                overlayUtils.addAllPagesCarsMarker();
            }
        }

    }

    @Override
    protected void onPause() {
        if (!isFirstLocation) {
            mLocClient.stop();
            mLocClient.unRegisterLocationListener(mListener);
        }
        //未允许定位权限，地图不执行onPause;这是为了解决：进入首页，弹出申请定位权限对话框，首页onPause,此时地图还未渲染完导致页面黑屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mapView.onPause();
            }
        } else {
            mapView.onPause();
        }

        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        SPUtils.getInstance(mContext).putLongValue(SPKey.REFRESH_TIME, 0);

        // 退出时销毁定位
        if (mLocClient != null) {
            mLocClient.stop();
        }
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        MapView.setMapCustomEnable(false);
        mapView.onDestroy();
        BaiduMapRoutePlan.finish(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        // OCR释放内存资源
        if (OCR.getInstance(this) != null) {
            OCR.getInstance(this).release();
        }
        super.onDestroy();

    }


    /**
     * @param view       布局
     * @param showOrHide true出现  false消失
     */

    private void setAnimator(final View view, final float start, float end, boolean showOrHide) {
        ObjectAnimator animator;
        animator = ObjectAnimator.ofFloat(view, "translationY", DensityUtils.dp2px(mContext, start), DensityUtils.dp2px(mContext, end));
        animator.setDuration(500L);
        if (showOrHide) {
            view.setVisibility(View.VISIBLE);
            if (view == layout_find_car) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                        //动画结束后，显示停车费提示
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) findCarFee.getLayoutParams();
                        params.setMargins(0, 0, 0, DensityUtils.dp2px(mContext, start + 8));
                        findCarFee.setLayoutParams(params);
                        findCarFee.setVisibility(View.VISIBLE);

                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
            }

        } else {
            if (view == layout_car_pager || view == layout_find_car) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                        layout_car_pager.setVisibility(View.GONE);
                        layout_find_car.setVisibility(View.GONE);
                        findCarFee.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
            }
        }
        animator.start();
    }

    //返回键弹出布局消失
    @Override
    public void onBackPressed() {
        backPress(true);
    }

    private void backPress(boolean isToBackground) {//单击地图不退到后台，按返回键可退到后台
        if (!isAnimatorShow && StateType.isEqualsCurStates(StateType.State.SHOW_PAGER)) {//动画没进行，显示车详情时

            compositeDisposable.clear();//取消还车备注的获取，取消寻车轨迹的获取
            overlayUtils.clearSelectedMarker();
            overlayUtils.hideInfoWindow();
            controlLayout(layout_car_pager, false, null);
            overlayUtils.removeNearTwentyMarker();
            StateType.setCurState(StateType.State.DEFAULT);
            getParksAndCarsByPages(true, false);


        } else if (!isAnimatorShow && isToBackground) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            try {
                startActivity(intent);
            } catch (Exception ignored) {
                AppManager.getAppManager().AppExit(mContext);
            }
        }
    }

    /**
     * isContinue
     * 不传或者为false：保持离开MainActivity时的状态;
     * true: MainActivity页面的内容重置，此时如果isLogin为true,检查未完成订单，initApp();
     * chooseCar
     * 不传或者为false: 不执行动作
     * true: WebView中点击"我要用车"跳转来，切换至汽车，跳出资格认证流程
     */

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int jumpCode = intent.getIntExtra("jumpCode", 0);
        if (jumpCode == 1) {//检查订单，不清除页面（登陆后）
            Logger.i("bounds", "onNewIntent");
            dialogQueue.dismissAllDialog();
            isFirstLocation = true;
            isFirstLocationError = true;
            if (couponCountdown != null)
                couponCountdown.setVisible(View.GONE);
            RxBus.getInstance().post(new CountDownCloseEvent(true));
            initBoundObservable(false);
            resetStatus(false, false);
            mapStatusUtils.noAnimateMove(curPosition, 11.5f);

        } else if (jumpCode == 4) {//有订单，直接进入订单，不提示是否进入订单；(退保证金，有订单)
            if (!StateType.isEqualsCurStates(StateType.State.CAR_FIND)) { //如果当前显示的就是寻车中，不查询
                isExecuteOnResumeCheckOrder = false;//不在执行onResume方法
                isLoadingDone = false;
                hasExistingTravelDirectlyIn();
            }
        } else if (jumpCode == 6) {//不检查订单,清除（退出登录后）
            isExecuteOnResumeCheckOrder = false;//不在执行onResume方法
            drawer.closeDrawer(Gravity.START);
            resetStatus(false, true);
            isLoadingDone = true;
            if (timer != null) {
                timer.cancel();
            }
        } else if (jumpCode == 0) {
            SPUtils.getInstance(mContext).putLongValue(SPKey.REFRESH_TIME, 0);
            resetStatus(false, true);
            isLoadingDone = true;
            if (timer != null) {
                timer.cancel();
            }
            drawer.closeDrawer(Gravity.START);
        } else if (jumpCode == 7) {
            SPUtils.getInstance(mContext).putLongValue(SPKey.REFRESH_TIME, 0);
            resetStatus(false, true);
            isLoadingDone = true;
            if (timer != null) {
                timer.cancel();
            }
            drawer.closeDrawer(Gravity.START);
        }
        String intent_zhima = intent.getStringExtra(SPKey.INTENT_ZHIMA);
        if ("MainActivity".equals(intent_zhima) || "ScanResultActivity".equals(intent_zhima)) {
            checkUserStatus();
        }
    }


    private void hasExistingTravelDirectlyIn() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getExistingTravel(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<ExistingTravel>() {
                    @Override
                    public void onResponse(Call<ExistingTravel> call, final Response<ExistingTravel> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (200 == response.body().getStatus()) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) { //有进行中的行程
                                    OrderRepository.orderId = response.body().getAttachment().getOrderId();
                                    OrderRepository.rentType = response.body().getAttachment().getRentType();
                                    OrderRepository.bookType = response.body().getAttachment().getOrderModel().getBookType();
                                    //送车上门订单，派单中或送车中（已送达）
                                    if (response.body().getAttachment().getPreOrder() != null) {
                                        OrderRepository.preOrderId = response.body().getAttachment().getPreOrder().getId();
                                        int preOrderStatus = response.body().getAttachment().getPreOrder().getStatus();
                                        if (!TextUtils.isEmpty(response.body().getAttachment().getPreOrder().getId())
                                                && (preOrderStatus == 0 || preOrderStatus == 1)) {
                                            resetStatus(true, true);
                                            Intent intent = new Intent(mContext, WebViewActivity.class);
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo)
                                                    + "?preOid=" + OrderRepository.preOrderId);
                                            CookieManager cookieManager = CookieManager.getInstance();
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo), "preOid=" + OrderRepository.preOrderId);
                                            startActivity(intent);
                                            return;
                                        }
                                    }
                                    // 其他订单
                                    switch (response.body().getAttachment().getStatus()) {
                                        case 0:
                                            updateFindCarInfo();
                                            isLoadingDone = true;
                                            break;
                                        case 10: {
                                            resetStatus(true, true);
                                            Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                            intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, response.body().getAttachment().getOrderId());
                                            startActivity(intentInUse);
                                            isLoadingDone = true;
                                        }
                                        break;
                                        case 15: {
                                            resetStatus(true, true);
                                            Intent intent = new Intent(mContext, WebViewActivity.class);
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                            CookieManager cookieManager = CookieManager.getInstance();
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + OrderRepository.orderId);
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + OrderRepository.orderId);
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + OrderRepository.rentType);
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + OrderRepository.bookType);
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL,
                                                    UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment)
                                                            + "?oid=" + OrderRepository.orderId + "&rentType=" + OrderRepository.rentType + "&bookType=" + OrderRepository.bookType);
                                            startActivity(intent);
                                            isLoadingDone = true;
                                        }
                                        break;
                                    }
                                }
                            } else if (20 == response.body().getStatus()) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ExistingTravel> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.d("netError", "032" + t);
                    }
                });
    }


    //修正寻车中的倒计时时间
    private void checkOrderStatus(boolean showLoading) {
        if (showLoading) {
            showLoadingDialog();
        }
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getExistingTravel(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<ExistingTravel>() {
                    @Override
                    public void onResponse(Call<ExistingTravel> call, final Response<ExistingTravel> response) {
                        dismissLoadingDialog();
                        if (response.isSuccessful() && response.body() != null) {
                            if (200 == response.body().getStatus()) {
                                //有寻车中的订单
                                //倒计时结束时，从服务器查询订单状态(订单是否真正超时)
                                long overPlusTime = 0;
                                if (response.body().getAttachment().getIsUnfinished() != 0 && response.body().getAttachment().getStatus() == 0) { //有进行中的行程
                                    OrderRepository.overPlusTime = response.body().getAttachment().getOrderModel().getOverplusTime() * 1000 + 2000;
                                    OrderRepository.totalTime = response.body().getAttachment().getCarFindTime() * 1000;
                                } else {
                                    OrderRepository.overPlusTime = 1000;
                                }
                                if (timer != null) {
                                    timer.cancel();
                                }
                                findCarTimer();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ExistingTravel> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }


    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            int mCurrentDirection = (int) x;
            if (curPosition != null) {
                locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccuracy)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mCurrentDirection).latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();
                mBaiduMap.setMyLocationData(locData);
            }
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    private boolean isFirstLocationError = true;

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mapView == null) {
                dismissLoadingDialog();
                DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                dialogOneButton.setMessage("定位异常，请退出应用再试。");
                dialogOneButton.setCancelable(false);
                dialogOneButton.setCanceledOnTouchOutside(false);
                dialogOneButton.setYesOnclickListener("确定", () -> AppManager.getAppManager().AppExit(mContext));
                dialogQueue.showDialog(dialogOneButton);
                return;
            }
            int locationErrorCode = bdLocation.getLocType();

            if (locationErrorCode == BDLocation.TypeGpsLocation || locationErrorCode == TypeNetWorkLocation || locationErrorCode == TypeOffLineLocation) {
                //GPS或者网络定位成功
                DecimalFormat df = new DecimalFormat("#.0000000");
                bdLocation = LocationFilter.Algorithm(bdLocation);//根据历史定位，对定位的结果平滑过滤
                if (!BuildConfig.DEBUG) {
                    if ((null != bdLocation.getCityCode()) && (null != MyApplication.getInstance().getAreaCode()) && (!MyApplication.getInstance().getAreaCode().equals(bdLocation.getCityCode()))) {
                        getCityInfo();
                    }
                    curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                    MyApplication.getInstance().setAreaCode(bdLocation.getCityCode());
                    MyApplication.getInstance().setAdCode(bdLocation.getAdCode());
                    MyApplication.getInstance().setCurPosition(df.format(curPosition.latitude), df.format(curPosition.longitude));
                    SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, bdLocation.getCity());
                } else {
                    switch (SPUtils.getInstance(mContext).getIntValue("$s_locationMode")) {
                        case 0:
                        case 1:
                            if ((null != MyApplication.getInstance().getAreaCode()) && (!MyApplication.getInstance().getAreaCode().equals(bdLocation.getCityCode()))) {
                                getCityInfo();
                            }
                            curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                            MyApplication.getInstance().setAreaCode(bdLocation.getCityCode());
                            MyApplication.getInstance().setAdCode(bdLocation.getAdCode());
                            MyApplication.getInstance().setCurPosition(df.format(curPosition.latitude), df.format(curPosition.longitude));
                            SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, bdLocation.getCity());

                            break;
                        case 2:
                            curPosition = new LatLng(Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude")),
                                    Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude")));// 更新定位
                            Logger.d(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                            MyApplication.getInstance().setAreaCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                            MyApplication.getInstance().setAdCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE));
                            MyApplication.getInstance().setCurPosition(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude"),
                                    SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude"));
                            break;
                    }

                }


                mCurrentAccuracy = bdLocation.getRadius();
                locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccuracy)
                        .direction(bdLocation.getDirection())// 此处设置开发者获取到的方向信息，顺时针0-360
                        .latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();
                mBaiduMap.setMyLocationData(locData);

                if (isFirstLocation) {//首次成功的定位
                    isFirstLocation = false;
                    Logger.i("bounds", "首次定位成功");
                    mapStatusUtils.noAnimateMove(curPosition, 11.5f);
                    //定位成功发送通知
                    RxBus.getInstance().post(new OnLocationDoneEvent(true));
                }

                if (StateType.isEqualsCurStates(StateType.State.CAR_FIND) && null != foundCarPosition) {
                    Logger.d("distance1", DistanceUtil.getDistance(curPosition, foundCarPosition) + "");
                    if (DistanceUtil.getDistance(curPosition, foundCarPosition)
                            <= SPUtils.getInstance(mContext).getIntValue(SPKey.FIND_CAR_DISTANCE)) {
                        find_car_open.setVisibility(View.VISIBLE);
                        find_car_find.setVisibility(View.VISIBLE);
                        find_car_qipao.setVisibility(View.GONE);
                    }
                }
                //计算显示不显示long-click-tip
                if (!isFirstLocation && !firstCalculateDistance) {
                    firstCalculateDistance = true;
                    if (overlayUtils.isShowNearCar(curPosition)) {
                        //long_click_tip.setVisibility(View.VISIBLE);
                    } else {
                        long_click_tip.setVisibility(View.GONE);
                    }
                }

            } else {//定位失败
                Logger.i("curPositionMainError", bdLocation.getLocType() + "");
                if (isFirstLocation && isFirstLocationError) {  //第一次定位失败执行，之后的失败定位不再执行
                    isFirstLocationError = false;
                    splash.setVisibility(View.GONE);
                    dismissLoadingDialog();
                    if (locationErrorCode == TypeServerError) {  //缺少定位权限
                        final DialogTwoButton dialogButton = new DialogTwoButton(mContext);
                        dialogButton.setTitle("定位权限已关闭");
                        dialogButton.setMessage("您需要开启定位权限，才可以查看车辆情况，请到设置的权限管理中开启【大道用的】定位权限。");
                        dialogButton.setCancelable(false);
                        dialogButton.setCanceledOnTouchOutside(false);
                        dialogButton.setYesOnclickListener("设置", () -> {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                            dialogButton.dismiss();
                        });
                        dialogButton.setNoOnclickListener("取消", () -> {
                            dialogButton.dismiss();
                        });
                        dialogQueue.showDialog(dialogButton);

                    } else {
                        final DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
                        dialogTwoButton.setTitle("定位服务已关闭");
                        dialogTwoButton.setCancelable(false);
                        dialogTwoButton.setCanceledOnTouchOutside(false);
                        dialogTwoButton.setMessage("您需要开启定位服务，才可以查看车辆情况，请到设置中开启定位服务。");
                        dialogTwoButton.setYesOnclickListener("设置", () -> {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                            dialogTwoButton.dismiss();
                        });
                        dialogTwoButton.setNoOnclickListener("取消", () -> {
                            dialogTwoButton.dismiss();
                        });
                        dialogQueue.showDialog(dialogTwoButton);
                    }
                }
            }
        }
    };

    private void notifyPeccancy() {
        String uid = SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID);
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).notifyPeccancy(MyApplication.getInstance().getRequestFieldMap(), uid).enqueue(new Callback<CheckPeccancyBean>() {
            @Override
            public void onResponse(Call<CheckPeccancyBean> call, Response<CheckPeccancyBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getCode() == 200) {

                    } else {
                        //ToastUtils.makeText(mContext, response.body().getMessage() + "。", ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    //ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckPeccancyBean> call, Throwable t) {
                //ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });

    }

    private void checkPeccancy() {
        String uid = SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID);
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkPeccancy(MyApplication.getInstance().getRequestFieldMap(), uid).enqueue(new Callback<CheckPeccancyBean>() {
            @Override
            public void onResponse(Call<CheckPeccancyBean> call, Response<CheckPeccancyBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (response.body().getData().isIs_new()) {
                            imageViewCenter.setImageDrawable(getResources().getDrawable(R.drawable.icon_center_dot));
                            iv_weizhang_reddot.setVisibility(View.VISIBLE);
                        }
                    } else {
                        //ToastUtils.makeText(mContext, response.body().getMessage() + "。", ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    //ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckPeccancyBean> call, Throwable t) {
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 清除主页面的地图和选车等布局
     */
    private void resetStatus(boolean isLoadMarker, boolean isShowLoading) {
        StateType.setCurState(StateType.State.DEFAULT);
        mapStatusUtils.noAnimateMove(curPosition, 17);
        layout_car_pager.setVisibility(View.GONE);
        layout_find_car.setVisibility(View.GONE);
        setAnimator(imageViewLocate, 0, 0f, false);
        setAnimator(imageViewCenter, 0, 0f, false);
        findCarFee.setVisibility(View.GONE);
        overlayUtils.clearMap();
        if (isLoadMarker) {
            getParksAndCarsByPages(isShowLoading, true);
        }
    }

    private void startLocation() {
        if (mLocClient != null) {
            mLocClient.stop();
            mLocClient.unRegisterLocationListener(mListener);
            mLocClient = null;
        }
        // 定位初始化
        mLocClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        if (BuildConfig.DEBUG) {
            option.setEnableSimulateGps(true);
        }
        option.setScanSpan(8000);
        mLocClient.setLocOption(option);
        mLocClient.registerLocationListener(mListener);
        if (null != mLocClient) mLocClient.restart();
    }

    private void showCancelOrder(String totalCancelTimes) {
        if (OrderRepository.bookType == 4) {
            Intent intent = new Intent();
            intent.setClass(mContext, WebViewActivity.class);
            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL,
                    UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_cancle)
                            + "?oid=" + OrderRepository.orderId + "&preOid=" + OrderRepository.preOrderId + "&rentType=" + OrderRepository.rentType + "&bookType=" + OrderRepository.bookType);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_cancle), "oid=" + OrderRepository.orderId);
            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_cancle), "preOid=" + OrderRepository.preOrderId);
            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_cancle), "rentType=" + OrderRepository.rentType);
            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_cancle), "bookType=" + OrderRepository.bookType);
            startActivity(intent);
            return;
        }
        final DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
        dialogTwoButton.setTitle("提醒");
        dialogTwoButton.setMessage("今天还可取消" + totalCancelTimes + "次");
        dialogTwoButton.setYesOnclickListener("继续用车", () -> dialogTwoButton.dismiss());
        dialogTwoButton.setNoOnclickListener("取消订单", () -> {
            cancelCarOrder();
            dialogTwoButton.dismiss();
        });
        dialogQueue.showDialog(dialogTwoButton);
    }


    //初始化OCR单利
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new com.baidu.ocr.sdk.OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Logger.i("OCRTOKEN", error.getMessage());
            }
        }, mContext);
    }

    // 在线活体检测和公安核实需要使用该token，为了防止ak、sk泄露，建议在线活体检测和公安接口在您的服务端请求
    private void initPoliceAccessToken() {

        APIService.getInstance().init(mContext);
        APIService.getInstance().initAccessTokenWithAkSk(new PoliceOnResultListener<PoliceAccessToken>() {
            @Override
            public void onResult(PoliceAccessToken result) {
                if (result != null && !TextUtils.isEmpty(result.getAccessToken())) {
                    Logger.i("RENLIAN", "policeToken ok");
                } else if (result != null) {
                    Logger.i("RENLIAN", "policeToken error null");
                } else {
                    Logger.i("RENLIAN", "policeToken error");
                }
            }

            @Override
            public void onError(FaceException error) {
                Logger.i("RENLIAN", "在线活体token获取 失败" + error.getErrorMessage());
            }
        }, Config.apiKey, Config.secretKey);
    }

    public void getZhiMaShouQuanUrl() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getZhiMaAuthorizeUrl(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<ZhiMaShouQuanBean>() {
            @Override
            public void onResponse(Call<ZhiMaShouQuanBean> call, Response<ZhiMaShouQuanBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        dismissLoadingDialog();
                        String url = response.body().getAttachment().getUrl();
                        doVerify(url);
                    } else if (response.body().getStatus() == 401) {
                        dismissLoadingDialog();
                        final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                        inCarDialog.setTitle("提示");
                        inCarDialog.setMessage(response.body().getMessage());
                        inCarDialog.setYesOnclickListener("查看说明", () -> {
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_zhima_break_rule));
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "文明用车倡议书");
                            startActivity(intent);
                            inCarDialog.dismiss();
                        });
                        inCarDialog.setNoOnclickListener("好的", () -> inCarDialog.dismiss());
                        dialogQueue.showDialog(inCarDialog);
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ZhiMaShouQuanBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            SPUtils.getInstance(mContext).putStringValue(SPKey.INTENT_ZHIMA, "MainActivity");
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            // 这里使用固定appid 20000067
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
        } else {
            // 处理没有安装支付宝的情况
            new android.app.AlertDialog.Builder(this)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", (dialog, which) -> {
                        Intent action = new Intent(Intent.ACTION_VIEW);
                        action.setData(Uri.parse("https://m.alipay.com"));
                        startActivity(action);
                    }).setNegativeButton("算了", (dialog, which) -> dialog.dismiss()).show();
        }
    }

    /**
     * 判断是否安装了支付宝
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

    private void checkUserStatus() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getUserStatus(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_AMOUNT, response.body().getAttachment().getCarBail() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.JISHEN_STATUS, response.body().getAttachment().getStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_STATUS, response.body().getAttachment().getAuthorize() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_FEN, response.body().getAttachment().getScore() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.XINYONG_LEVEL, response.body().getAttachment().getLevel() + "");
                        if ("1".equals(response.body().getAttachment().getUserZmInfo())) {
                            if ("1".equals(response.body().getAttachment().getAuthorize() + "")) {

                            } else {
                                final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                                dialogOneButton.setTitle("您的芝麻信用分值不足");
                                dialogOneButton.setMessage("请用保证金方式进行信用认证");
                                dialogOneButton.setCancelable(false);
                                dialogOneButton.setCanceledOnTouchOutside(false);
                                dialogOneButton.setYesOnclickListener("知道了", () -> dialogOneButton.dismiss());
                                dialogOneButton.show();
                            }
                        } else {
                            ToastUtils.makeText(mContext, "授权失败，请重新尝试", ToastUtils.LENGTH_SHORT).show();
                        }


                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //开启定位服务返回结果
        if (requestCode == Constants.REQUEST_LOCATION_SERVICE) {
            initLocationService();
            startLocation();
        }
    }


    public void getUnOrder(OrderRepository.GetUnfinishedOrderDone getUnfinishedOrderDone) {
        OrderRepository.getUnfinishedOrder().observeForever(unFinishedOrderBeanResource ->
                unFinishedOrderBeanResource.handle(new Resource.OnCallBack<UnFinishedOrderBean>() {
                    @Override
                    public void onStatusSuccess(UnFinishedOrderBean data) {
                        //没有进行中订单
                        if (data.getIsUnfinished() == 0) {
                            isLoadingDone = true;
                            getUnfinishedOrderDone.onNoOrder();
                            return;
                        }
                        //有进行中的行程
                        getUnfinishedOrderDone.onHaveOrder(data);
                        OrderRepository.orderId = data.getOrderId();
                        OrderRepository.rentType = data.getRentType();
                        OrderRepository.bookType = data.getOrderModel().getBookType();

                        //送车上门订单，派单中或送车中（已送达）
                        if (data.getPreOrder() != null) {
                            OrderRepository.preOrderId = data.getPreOrder().getId();
                            int preOrderStatus = data.getPreOrder().getStatus();
                            if (!TextUtils.isEmpty(data.getPreOrder().getId())
                                    && (preOrderStatus == 0 || preOrderStatus == 1)) {

                                unFinishTravelDialog.setTitle("提醒");
                                unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                unFinishTravelDialog.setYesOnclickListener("进入", () -> {
                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo) + "?preOid=" + OrderRepository.preOrderId);
                                    CookieManager cookieManager = CookieManager.getInstance();
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo), "preOid=" + OrderRepository.preOrderId);
                                    startActivity(intent);
                                    unFinishTravelDialog.dismiss();
                                });
                                unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                unFinishTravelDialog.setCancelable(false);
                                dialogQueue.showDialog(unFinishTravelDialog);
                                return;
                            }
                        }
                        // 其他订单
                        switch (data.getStatus()) {
                            case 0:
                                isLoadingDone = true;
                                unFinishTravelDialog.setTitle("提醒");
                                unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                unFinishTravelDialog.setYesOnclickListener("进入", () -> {
                                    updateFindCarInfo();
                                    unFinishTravelDialog.dismiss();
                                });
                                unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                dialogQueue.showDialog(unFinishTravelDialog);
                                break;
                            case 10:
                                unFinishTravelDialog.setTitle("提醒");
                                unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                unFinishTravelDialog.setYesOnclickListener("进入", () -> {
                                    Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                    intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, OrderRepository.orderId);
                                    startActivity(intentInUse);
                                    unFinishTravelDialog.dismiss();
                                });
                                unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                unFinishTravelDialog.setCancelable(false);
                                dialogQueue.showDialog(unFinishTravelDialog);
                                break;
                            case 15:
                                unFinishTravelDialog.setTitle("有未支付的订单");
                                unFinishTravelDialog.setMessage("支付后才能订车");
                                unFinishTravelDialog.setYesOnclickListener("支付", () -> {
                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                    CookieManager cookieManager = CookieManager.getInstance();
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + OrderRepository.orderId);
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + OrderRepository.orderId);
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + OrderRepository.rentType);
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + OrderRepository.bookType);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment)
                                            + "?oid=" + OrderRepository.orderId + "&rentType=" + OrderRepository.rentType + "&bookType=" + OrderRepository.bookType);
                                    startActivity(intent);
                                    unFinishTravelDialog.dismiss();
                                });
                                unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                unFinishTravelDialog.setCancelable(false);
                                dialogQueue.showDialog(unFinishTravelDialog);
                                break;
                        }
                    }

                    @Override
                    public void onStatusFailure(int status, String message, UnFinishedOrderBean data) {
                        getUnfinishedOrderDone.onError(message);
                    }

                    @Override
                    public void onLoadError(Throwable error) {
                        getUnfinishedOrderDone.onError(getResources().getString(R.string.badNetwork));
                    }
                }));

    }

}